题目一
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> list = new ArrayList<List<Integer>>();
public int maxDepth(TreeNode root) {
method(0,root);
return list.size();
}
public void method(int depth,TreeNode root){
if(root==null) return;
if(list.size()==depth){
list.add(new ArrayList<Integer>());
}
method(depth+1,root.left);
method(depth+1,root.right);
}
}
题目二
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode ans = root;
while(true){
if(p.val<ans.val&&q.val<ans.val){
ans = ans.left;
}else if(p.val>ans.val&&q.val>ans.val){
ans = ans.right;
}else{
break;
}
}
return ans;
}
}
题目三
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> list = new ArrayList<Integer>();
public TreeNode increasingBST(TreeNode root) {
method(root);
TreeNode tmp = new TreeNode(-1);
TreeNode ans = tmp;
for(int i:list){
tmp.right = new TreeNode(i);
tmp = tmp.right;
}
return ans.right;
}
public void method(TreeNode root){
if(root==null) return;
method(root.left);
list.add(root.val);
method(root.right);
}
}
题目四
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Set<Integer> set = new HashSet<Integer>();
public boolean findTarget(TreeNode root, int k) {
if (root == null) return false;
if (set.contains(k - root.val)) return true;
set.add(root.val);
return findTarget(root.left, k) || findTarget(root.right, k);
}
}
题目五
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return method(nums,0,nums.length-1);
}
public TreeNode method(int[] nums,int low,int high){
if(low>high) return null;
int mid = low+(high-low)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = method(nums,low,mid-1);
root.right = method(nums,mid+1,high);
return root;
}
}