原题链接在这里:https://leetcode.com/problems/balance-a-binary-search-tree/
题目:
Given the root
of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1
.
Example 1:
Input: root = [1,null,2,null,3,null,4,null,null] Output: [2,1,3,null,null,null,4] Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.
Example 2:
Input: root = [2,1,3] Output: [2,1,3]
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. 1 <= Node.val <= 105
题解:
Could perform a inorder traverse first and then construst balanced BST from inorder list.
TimeComplexity: O(n). n is total number of numbers in the tree.
Space: O(n). list size.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 List<TreeNode> list = new ArrayList<>(); 18 public TreeNode balanceBST(TreeNode root) { 19 inorderDfs(root); 20 return constructBalancedBst(0, list.size() - 1); 21 } 22 23 private void inorderDfs(TreeNode root){ 24 if(root == null){ 25 return; 26 } 27 28 inorderDfs(root.left); 29 list.add(root); 30 inorderDfs(root.right); 31 } 32 33 private TreeNode constructBalancedBst(int l, int r){ 34 if(l > r){ 35 return null; 36 } 37 38 int mid = l + (r - l) / 2; 39 TreeNode root = list.get(mid); 40 root.left = constructBalancedBst(l, mid - 1); 41 root.right = constructBalancedBst(mid + 1, r); 42 return root; 43 } 44 }
类似Convert Sorted Array to Binary Search Tree.
标签:Binary,Search,TreeNode,val,tree,Tree,return,null,root From: https://www.cnblogs.com/Dylan-Java-NYC/p/16727874.html