Leetcode 110. 平衡二叉树
题目链接:110. 平衡二叉树
思路
我觉得这道题值得学习的地方在于,在一些情况下返回 -1。因为一开始想到了要求左右子树的高度,但是纠结的地方在于,如果此时不满足平衡二叉树,我要返回什么值给父节点。因为递归函数定义的返回值是 int,那就不可能返回 boolean 类型的值。
代码实现
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;
}
}
Leetcode 257. 二叉树的所有路径
题目链接:257. 二叉树的所有路径
这道题涉及回溯的过程。回溯和递归是一一对应的,有一个递归,就要有一个回溯。
代码实现
class Solution {
List<String> result = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
List<Integer> path = new ArrayList<>();
if(root == null){
return result;
}
traversal(root, path);
return result;
}
public void traversal(TreeNode root, List<Integer> path){
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));
result.add(sb.toString());
return;
}
if(root.left != null){
traversal(root.left, path);
path.remove(path.size() - 1);
}
if(root.right != null){
traversal(root.right, path);
path.remove(path.size() - 1);
}
}
}
Leetcode 404. 左叶子之和
题目链接:404. 左叶子之和
平时我们解二叉树的题目时,已经习惯了通过节点的左右孩子判断本节点的属性,而本题我们要通过节点的父节点判断本节点的属性。
看了题解,觉得有点绕,它是通过判断一个节点的左节点不为空,该节点的左节点的左节点为空,该节点的左节点的右节点为空,则证明找到了一个左叶子。
解题:成功
代码实现(更容易理解)
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
dfs(root, false);
return sum;
}
public void dfs(TreeNode root, boolean isLeft){
if(root.left == null && root.right == null && isLeft){
sum += root.val;
return;
}
if(root.left != null){
dfs(root.left, true);
}
if(root.right != null){
dfs(root.right, false);
}
}
}
代码实现(题解版)
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null){
return 0;
}
// 这个判断语句可写可不写,写了可以减少一次递归
if(root.left == null && root.right == null){
return 0;
}
int leftValue = sumOfLeftLeaves(root.left); //左
if(root.left != null && root.left.left == null && root.left.right == null){
leftValue = root.left.val;
}
int rightValue = sumOfLeftLeaves(root.right); //右
int sum = leftValue + rightValue; //中
return sum;
}
}