129. 求根节点到叶节点数字之和
题目链接:129. 求根节点到叶节点数字之和 - 力扣(LeetCode)
题目难度:中等
代码:
class Solution {
List<Integer> path=new ArrayList<>();
int res=0;
public int sumNumbers(TreeNode root) {
if(root==null) return 0;
path.add(root.val);
recur(root);
return res;
}
public void recur(TreeNode root){
if(root.left==null&&root.right==null){
res+=listToInt(path);
return;
}
if(root.left!=null){
path.add(root.left.val);
recur(root.left);
path.remove(path.size()-1);
}
if(root.right!=null){
path.add(root.right.val);
recur(root.right);
path.remove(path.size()-1);
}
return;
}
public int listToInt(List<Integer> path){
int sum=0;
for(Integer num:path){
sum=sum*10+num;
}
return sum;
}
}
1382. 将二叉搜索树变平衡
题目链接:1382. 将二叉搜索树变平衡 - 力扣(LeetCode)
题目难度:中等
代码:
class Solution {
ArrayList<Integer> res=new ArrayList<>();
private void travesal(TreeNode cur){
if(cur==null) return;
travesal(cur.left);
res.add(cur.val);
travesal(cur.right);
}
private TreeNode getTree(ArrayList<Integer> nums,int left,int right){
if(left>right) return null;
int mid=left+(right-left)/2;
TreeNode root=new TreeNode(nums.get(mid));
root.left=getTree(nums,left,mid-1);
root.right=getTree(nums,mid+1,right);
return root;
}
public TreeNode balanceBST(TreeNode root) {
travesal(root);
return getTree(res,0,res.size()-1);
}
}
100. 相同的树
题目链接:100. 相同的树 - 力扣(LeetCode)
题目难度:简单
代码:
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
else if (q == null || p == null) return false;
else if (q.val != p.val) return false;
return isSameTree(q.left, p.left) && isSameTree(q.right, p.right);
}
}