1.题目描述
1.1笔者分析
对于这种高度平衡二叉树,我原来一直认为是很复杂的,左旋转右旋转的。没有想到一个二分就解决了。
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return help(nums,0,nums.length-1);
}
TreeNode help(int[] nums,int l ,int r){
if(r<l)return null;
int mid=l+((r-l)>>1);
TreeNode root=new TreeNode(nums[mid]);
root.left=help(nums,l,mid-1);
root.right=help(nums,mid+1,r);
return root;
}
}
2.题目描述
2.1笔者分析
搜索树出题也太灵活多变了。
class Solution {
private int ans=0,count=0;
public int kthLargest(TreeNode root, int k) {
helper(root,k);
return ans;
}
private void helper(TreeNode root,int k){
if(root.right!=null) helper(root.right,k);
if(++count==k){
ans=root.val;
return ;
}
if(root.left!=null)helper(root.left,k);
}
}
3.题目描述
3.1笔者分析
对树的理解不能仅限于递归,像这题借用队列同样可以解决问题,一定要考虑是否可以借用其它数据结构来辅助。
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null)return new ArrayList<>();
List<List<Integer>> res=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(root);
int count;
while(!queue.isEmpty()){
count=queue.size();
List<Integer> list=new ArrayList<Integer>();
while(count>0){
TreeNode node=queue.poll();
list.add(node.val);
if(node.left!=null)queue.add(node.left);
if(node.right!=null)queue.add(node.right);
count--;
}
res.add(list);
}
return res;
}
}
总结
每日十题打卡,第四十四天,以下图为证