目录
平衡二叉树
文章讲解:代码随想录
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
int left = Depth(root.left);
int right = Depth(root.right);
if(Math.abs(left-right)>1)
return false;
boolean l = isBalanced(root.left);
boolean r = isBalanced(root.right);
return l && r;
}
//找出树的最大深度
public int Depth(TreeNode node){
if(node == null){
return 0;
}
int left = Depth(node.left);
int right = Depth(node.right);
return Math.max(left,right)+1;
}
}
二叉树的所有路径
文章讲解:代码随想录
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if(root == null)
return list;
function(root,list,"");
return list;
}
public void function(TreeNode root,List<String> list,String path){
if(root != null){
StringBuilder str = new StringBuilder();
str.append(path);
str.append(String.valueOf(root.val));
if(root.left == null && root.right == null){
list.add(str.toString());
}else{
str.append("->");
function(root.left,list,str.toString());
function(root.right,list,str.toString());
}
}
}
}
左叶子之和
文章讲解:代码随想录
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null)
return 0;
int leftValue = sumOfLeftLeaves(root.left);
int rightValue = sumOfLeftLeaves(root.right);
int value = 0;
if(root.left!=null && root.left.left==null&&root.left.right==null){
value = root.left.val;
}
int sum = value+leftValue+rightValue;
return sum;
}
}