110.平衡二叉树
题目链接:110. 平衡二叉树 - 力扣(LeetCode)
递归写法:
核心思想还是求每个子树的最大高度,然后判断是否是平衡二叉树,如果不是直接不返回深度了,返回-1,这样就可以通过返回值判断是否是平衡二叉树了。返回的是正数就代表平衡,返回的-1就代表不平衡。
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1 ? true : false;
}
int getHeight(TreeNode root){
if(root == null) return 0;
// 计算左右子树的最大高度
int leftmax = getHeight(root.left); // 左
if(leftmax == -1) return -1;
int rightmax = getHeight(root.right); // 右
if(rightmax == -1) return -1;
// 至此左右子树都是平衡的
if(Math.abs(rightmax - leftmax) > 1) return -1; // 中
return Math.max(leftmax, rightmax) + 1;
}
}
迭代写法:此题迭代法过于复杂,暂时略
本题中涉及到的树的高度和深度的理解可以多思考思考:
其中树的高度是从下向上计算的,也就是遍历顺序先下后上,也就是前序遍历,左右中。
树的深度是从上向下计算的,也就是遍历顺序先上后下,也就是后序遍历,中左右。
根节点的深度是最小的,高度则是整个树中最大的。
257.二叉树的所有路径
题目链接:257. 二叉树的所有路径 - 力扣(LeetCode)
回溯法:
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
if(root == null) return ans;
findpaths(root, path, ans);
return ans;
}
void findpaths(TreeNode root,List<Integer> path, List<String> ans){
path.add(root.val); // 路径是一个列表的形式
// 迭代的终止条件
if(root.left == null && root.right == null){
StringBuilder sbpath = new StringBuilder();
for(int i = 0; i < path.size() - 1; i++){
sbpath.append(path.get(i)).append("->");
}
sbpath.append(path.get(path.size() - 1));
ans.add(sbpath.toString());
return;
}
if(root.left != null){
// path.add(root.val);
findpaths(root.left, path, ans);
path.remove(path.size() - 1);
}
if(root.right != null){
// path.add(root.val);
findpaths(root.right, path, ans);
path.remove(path.size() - 1);
}
}
}
这里path.add(root.val);如果拿到每个if语句当中执行结果就会有问题,没想清楚具体因为什么
404.左叶子之和
题目链接:404. 左叶子之和 - 力扣(LeetCode)
递归解法:
该题目递归的时候,使用一个标志位flag来标志当前节点是否是左孩子节点,是就为1,不是就为0。
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
if(root == null) return 0;
getsum(root,0);
return sum;
}
void getsum(TreeNode root, int flag){ // flag = 0 不是左孩子 1 是左孩子
if(flag == 1 && root.left == null && root.right == null){
sum += root.val;
}
if(root.left == null && root.right == null) return;
if(root.left != null) getsum(root.left, 1);
if(root.right != null) getsum(root.right, 0);
}
}