今日任务
110. 平衡二叉树 257. 二叉树的所有路径
404. 左叶子之和
代码随想录
110. 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
这题我首先想到的思路是使用后序遍历先求左右子树的高度,然后在根据高度差判断平衡即可,但是根据这种想法直接写有部分实例通不过,在中间结点有空子树的情况下行不通,需要再分别判断左右子树是否平衡(即拆分)。因为只要中间结点有空子树,那么这颗二叉树的高度一定是不平衡的。
🍅 递归解法,即重复调用函数来完成深度的叠加(后序遍历)
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
return Math.abs(leftDepth-rightDepth) > 1? false : isBalanced(root.left) && isBalanced(root.right);
}
public int getDepth(TreeNode node){
if (node == null) return 0;
int left = getDepth(node.left); //左
int right = getDepth(node.right); //右
return Math.max(left,right)+1; //中
}
}
257. 二叉树的所有路径
给你一个二叉树的根节点
root,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
🍅 递归解法,采用dfs先序遍历递归。
这题我采用的方法是递归,我感觉回溯的过程还是挺重要的,还有就是因为要对字符串进行多次修改,所以采用StringBuilder来完成要放入答案的字符串,在放入的过程有些细节需要稍微注意一下。
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
List<Integer> paths = new ArrayList<>();
traversal(root,paths,res);
return res;
}
public void traversal(TreeNode root, List<Integer> paths, List<String> res) {
paths.add(root.val); //中
if(root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < paths.size() - 1; i++) {
sb.append(paths.get(i));
sb.append("->");
}
sb.append(paths.get(paths.size()-1));
res.add(sb.toString());
}
if(root.left != null) {
traversal(root.left, paths, res); //左
paths.remove(paths.size()-1); //回溯
}
if(root.right !=null) {
traversal(root.right, paths, res); //右
paths.remove(paths.size()-1); //回溯
}
}
}
404. 左叶子之和
给定二叉树的根节点
root,返回所有左叶子之和。
🍅 递归解法,采用后序遍历递归。
这题我采用的方法是后序递归遍历,要注意判断条件的位置应在左遍历下方。
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null) return 0;
int leftval = sumOfLeftLeaves(root.left); //左
if(root.left != null && root.left.left == null && root.left.right == null) {
leftval = root.left.val;
}
int rightval = sumOfLeftLeaves(root.right); //右
int sum = leftval + rightval; //中
return sum;
}
}