110. 平衡二叉树
思路
- 求深度的问题可以使用求高度的方式(深度:前序-中左右 高度:后序-左右中)
- 平衡二叉树 是指该树所有节点的左右子树的深度相差不超过 1。 判断的是当前节点的左右子节点的大小,不是最短的叶子节点和最长的叶子节点之间的深度 (最开始这里考虑的有问题,导致不确定向上返回是最大值还是最小值)
代码
class Solution {
public boolean isBalanced(TreeNode root) {
//求高度-后序-左右中
return getHeight(root)!=-1;
}
private int getHeight(TreeNode root){
if(root==null) return 0;
int left = getHeight(root.left);
if(left==-1) return -1;
int right = getHeight(root.right);
if(right==-1) return -1;
if(Math.abs(left-right)>1) {
return -1;
}else{
return 1+Math.max(left,right);
}
}
}
257. 二叉树的所有路径
关键点:前序遍历、回溯
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
List<Integer> path = new ArrayList<>();
getPath(root, list, path);
return list;
}
//前序遍历 回溯
private void getPath(TreeNode root, List<String> list, List<Integer> path){
//中
path.add(root.val);
if(root.left==null&&root.right==null){
StringBuilder str = new StringBuilder();
for(int i=0; i<path.size(); i++){
str.append(path.get(i));
if(i!=path.size()-1){
str.append("->");
}
}
list.add(str.toString());
return;
}
if(root.left!=null){
getPath(root.left, list, path);
path.remove(path.size()-1);
}
if(root.right!=null){
getPath(root.right, list, path);
path.remove(path.size()-1);
}
}
}
404. 左叶子之和(mmhh)
做之前不知道如何确定终止条件以及如何统计左节点
关键点:当前节点的左节点!=null && 当前节点的左节点的左节点和右节点都==null时,就该收集该节点的左节点
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
//做剪枝操作
//1.头节点为null的情况
if(root==null) return 0;
//2.遍历到叶子节点的情况
if(root.left==null && root.right==null) return 0;
//为了获取两边的总和 使用左右中-后序遍历
int leftNum = sumOfLeftLeaves(root.left);
int rightNum = sumOfLeftLeaves(root.right);
int mid = 0;
if(root.left!=null && root.left.left==null && root.left.right==null){
mid=root.left.val;
}
return leftNum+rightNum+mid;
}
}
222. 完全二叉树的节点个数
class Solution {
public int countNodes(TreeNode root) {
//后序遍历-左右中
if(root==null) return 0;
int left = 0;
int right = 0;
if(root.left!=null){
left = countNodes(root.left);
}
if(root.right!=null){
right = countNodes(root.right);
}
return 1+left+right;
}
}