110.平衡二叉树 (优先掌握递归)
解题先看定义
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
因为要计算每个node 左右子树的height,所以需要重新定义一个递归函数,返回当前节点为root的二叉树的高度。
优化:如果在某一个节点,左右子树已经不平衡了,也就是高度差大于1,没有比较继续计算高度,直接返回-1,表示该树不是二叉平衡树
* 求深度适合用前序遍历,而求高度适合用后序遍历。
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
private int height(TreeNode root){
//base case
if(root == null){
return 0;
}
//左
int leftHeight = height(root.left);
if(leftHeight == -1){
return -1;
}
//右
int rightHeight = height(root.right);
if (rightHeight == -1){
return -1;
}
//中
return Math.abs(leftHeight - rightHeight) <= 1 ? Math.max(leftHeight, rightHeight) + 1 : -1 ;
}
}
257. 二叉树的所有路径 (优先掌握递归)
这道题使用递归和回溯, 在遍历的过程度,记录遍历的节点,到达leaf 时,将结果放入List。
定义一个新的递归函数,节点,路径和结果集作为参数,不需要返回值。当找到leaf,左右子树为空,就终止递归
因为需要记录路径,所以为前序遍历
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
backTracking(root, path, ans);
return ans;
}
private void backTracking(TreeNode root, List<Integer> path, List<String> ans){
path.add(root.val);
// reach a leaf
if(root.left == null && root.right == null){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < path.size() - 1; i++){
sb.append(path.get(i)).append("->");
}
sb.append(path.get(path.size() - 1));
ans.add(sb.toString());
return;
}
if(root.left != null){
backTracking(root.left, path, ans);
path.remove(path.size() - 1);
}
if(root.right != null){
backTracking(root.right, path, ans);
path.remove(path.size() - 1);
}
}
}
404.左叶子之和 (优先掌握递归)
首先确定题意,左叶子首先是leaf, 而且是其parent的left child,所以这道题就是遍历所有node,通过父节点找到符合要求的左叶子。
确定终止条件:
如果遍历到空节点, 没有左叶子 ,return 0;
如果遍历到 叶子,也没有左叶子,return 0;
递归逻辑:
在父节点检测到左叶子,记录数值。递归求取左子树左叶子之和,和 右子树左叶子之和,然后返回数值之和。
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return 0;
int leftValue = sumOfLeftLeaves(root.left);
//left leaf
if (root.left != null && root.left.left ==null && root.left.right== null){
leftValue = root.left.val;
}
int rightValue = sumOfLeftLeaves(root.right);
return leftValue + rightValue;
}
}
222.完全二叉树的节点个数(优先掌握递归)
class Solution {
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
2773



被折叠的 条评论
为什么被折叠?



