leetcode110.平衡二叉树
注意:×
- -1 表示已经不是平衡二叉树了,否则返回值是以该节点为根节点树的高度
int getHeight(TreeNode* node)
- 注意对leftDep和rightDep进行提前判断
- !!!!!!!!!!!!!!!!!getDep函数返回的时候注意
Math.max(leftDep,rightDep)+1
public boolean isBalanced(TreeNode root) {
if (root == null){
return true;
}else {
return Math.abs(getDep(root.left) - getDep(root.right)) <= 1;
}
}
int getDep(TreeNode node){
if (node == null){
return 0;
}
int leftDep = getDep(node.left);
if (leftDep==-1){
return -1;
}
int rightDep = getDep(node.right);
if (rightDep==-1){
return -1;
}
return Math.abs(leftDep-rightDep)>1 ? -1:Math.max(leftDep,rightDep)+1;
}
leetcode257. 二叉树的所有路径
注意:×
- 注意
List<String> paths = new ArrayList<String>();
List是继承ArrayList的 - 全新的traverse函数的传递方式,传递了
TreeNode root, String path, List<String> paths
- 一定要反复看的题目
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
constructPaths(root, "", paths);
return paths;
}
public void constructPaths(TreeNode root, String path, List<String> paths) {
if (root != null) {
StringBuffer pathSB = new StringBuffer(path);
pathSB.append(Integer.toString(root.val));
if (root.left == null && root.right == null) { // 当前节点是叶子节点
paths.add(pathSB.toString()); // 把路径加入到答案中
} else {
pathSB.append("->"); // 当前节点不是叶子节点,继续递归遍历
constructPaths(root.left, pathSB.toString(), paths);
constructPaths(root.right, pathSB.toString(), paths);
}
}
}
leetcode404.左叶子之和
注意:×
- 满巧妙的题目,额外使用res来进行补充
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
int res1 = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
res1 = root.left.val;
}
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right)+res1;
}