LeetCode110.平衡二叉树
public boolean isBalanced(TreeNode root) {
if(root==null) {
return true;
}
int res = countHeight(root);
if(res==-1) {
return false;
}
return true;
}
public int countHeight(TreeNode root) {
//递归结束条件,由于有可能没有左子树或右子树,所以最后结束要结束在null,不能结束在叶子结点
if(root==null) {
return 0;
}
//左递归
int left = countHeight(root.left);
if(left==-1) {
return -1;
}
//右递归
int right = countHeight(root.right);
if(right==-1) {
return -1;
}
//处理中间结点
if(Math.abs(left-right)>1) {
return -1;
}else {
return Math.max(left, right)+1;
}
}
LeetCode257.二叉树的所有路径
//存放结果数组
List<String> res = new ArrayList<>();
//存放join的数组
List<String> join = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root==null) {
return res;
}
join.add(String.valueOf(root.val));
dps(root);
return res;
}
public void dps(TreeNode root) {
//递归结束条件
if(root.left==null&&root.right==null) {
String str = String.join("->", join);
res.add(str);
return ;
}
//左递归
if(root.left!=null) {
join.add(String.valueOf(root.left.val));
dps(root.left);
join.remove(join.size()-1);
}
//右递归
if(root.right!=null) {
join.add(String.valueOf(root.right.val));
dps(root.right);
join.remove(join.size()-1);
}
}
LeetCode404..左叶子之和
public int leftNum=0;
public void in(TreeNode root,int bool) {
//判断左叶子结点
if(root.left==null&&root.right==null) {
if(bool==0) {
leftNum+=root.val;
}
return ;
}
if(root.left!=null) {
in(root.left,0);
}
if(root.right!=null) {
in(root.right,1);
}
}
public int sumOfLeftLeaves(TreeNode root) {
if(root==null) {
return 0;
}
if(root.left==null&&root.right==null) {
return 0;
}
in(root,0);
return leftNum;
}
LeetCode222.完全二叉树的节点个数
public int countNodes(TreeNode root) {
if(root==null) {
return 0;
}
if(root.left==null&&root.right==null) {
return 1;
}
return post(root);
}
public int post(TreeNode root) {
//递归结束条件
if(root==null) {
return 0;
}
//进行满二叉树判断
TreeNode left = root.left;
TreeNode right = root.right;
int leftNum=0,rightNum=0;
while(left!=null) {
leftNum++;
left=left.left;
}
while(right!=null) {
rightNum++;
right=right.right;
}
if(leftNum==rightNum) {
return (2 << leftNum) - 1;
}
//如果不命中则进入左右递归
return post(root.left)+post(root.right)+1;
}