110 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
这道题的重点在于:递归过程中如果左子树或者右子树有一个为-1,那就不是平衡二叉树了,本轮没必要再继续了,而且下一轮、下下轮...也可以直接返回了。
class Solution {
public boolean isBalanced(TreeNode root) {
return balance(root) != -1;
}
public int balance(TreeNode root){
if(root == null){
return 0;
}
int left = balance(root.left);
//如果是-1,那么不需要再判断本轮,直接返回回去
if(left == -1)
return -1;
int right = balance(root.right);
if(right == -1)
return -1;
//如果左右子树都符合平衡条件(都不是-1),那么就开始计算左右子树的高度差
if(Math.abs(left - right) <= 1){
return Math.max(left,right) + 1;
}
else{
return -1;
}
}
}
257.代码随想录
class Solution {
//定义一个全局变量
ArrayList<String> list = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
ArrayList<Integer> path = new ArrayList<>();
if(root == null){
return list;
}
//只有root不是null时才会加入递归方法
return deal(root,path);
}
public ArrayList<String> deal(TreeNode node,ArrayList<Integer> path){
path.add(node.val);
if(node.left != null){
//因为此时进行了判断,所以保证每次进入递归的都不是null
deal(node.left,path);
//递归完了以后要回溯;
path.remove(path.size() - 1);
}
if(node.right != null){
deal(node.right,path);
path.remove(path.size() - 1);
}
if(node.left == null && node.right == null){
StringBuilder sb = new StringBuilder();
for(int i = 0; i< path.size();i++){
if(i != path.size() - 1){
sb.append(path.get(i)).append("->");
}
else{
sb.append(path.get(i));
}
}
list.add(sb.toString());
}
return list;
}
}
404.
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return getSum(root);
}
public int getSum(TreeNode node){
int value = 0;
if(node== null){
return 0;
}
int left = getSum(node.left);
int right = getSum(node.right);
if(node.left != null && node.left.left == null && node.left.right == null){
value = node.left.val;
}
return value + left + right;
}
}