Leetcode 刷题Day17 ---------------二叉树
1. 平衡二叉树 (110)
- 题目链接:https://leetcode.cn/problems/balanced-binary-tree/
- 文章讲解/视频讲解:https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root)!=-1;
}
public int getHeight(TreeNode root){
if(root==null) return 0;
int leftHeight=getHeight(root.left);
if(leftHeight==-1) return -1;
int rightHeight=getHeight(root.right);
if(rightHeight==-1) return -1;
if(Math.abs(leftHeight-rightHeight)>1) return -1;
return Math.max(leftHeight,rightHeight)+1;
}
}
2. 二叉树的所有路径 (257)
根左右:前序遍历
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<Integer> path=new ArrayList<Integer>();//放单条路线的路径
List<String> res=new ArrayList<String>();//将每条路径保存为结果
if(root==null) return null;
traversal(root,path,res);
return res;
}
public void traversal(TreeNode root,List<Integer> path,List<String> res){
path.add(root.val);
if(root.left==null&&root.right==null){
StringBuilder sb=new StringBuilder();
for(int i=0;i<path.size()-1;i++){
sb.append(path.get(i)).append("->");
}
sb.append(path.get(path.size()-1));
res.add(sb.toString());
}
if(root.left!=null){
traversal(root.left,path,res);
path.remove(path.size()-1);//回退
}
if(root.right!=null){
traversal(root.right,path,res);
path.remove(path.size()-1);//回退
}
}
}
3. 左叶子之和 (404)
叶子:左右孩子都为空
左右中 后序遍历:从下往上遍历
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root==null) return 0;
if(root.left==null && root.right==null) return 0;
int leftSum=sumOfLeftLeaves(root.left);//20行
if(root.left!=null && root.left.left==null && root.left.right==null) leftSum=root.left.val;//21行
int rightSum=sumOfLeftLeaves(root.right);
//if(root.right!=null && root.right.left==null && root.right.right==null) leftSum=root.right.val;
return leftSum+rightSum;
}
}
20行先计算左子树的左叶子之和
21行是本节点的判断 直接给leftSum赋值的原因是 如果满足了if的那些条件 说明20行计算左子树的结果一定是0 所以直接赋值没问题 当然更好是用+=