学习任务:
- Leetcode110.平衡二叉树
- Leetcode257. 二叉树的所有路径
- Leetcode404.左叶子之和
- Leetcode222.完全二叉树的节点个数
Leetcode110.平衡二叉树
难度:简单
| 相关标签:树、深度优先搜索、二叉树
-
题目: 给定一个二叉树,判断它是否是 平衡二叉树
-
思路:
-
注意: 如何标记左右子树是否差值大于1呢?
如果当前传入节点为根节点的二叉树已经不是二叉平衡树了,还返回高度的话就没有意义了。
所以如果已经不是二叉平衡树了,可以返回-1 来标记已经不符合平衡树的规则了。 -
代码:
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
private int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = getHeight(root.left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = getHeight(root.right);
if (rightHeight == -1) {
return -1;
}
// 左右子树高度差大于1,return -1表示已经不是平衡树了
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
}
- 反思:
Leetcode257. 二叉树的所有路径 看不懂先跳过,后面再回来做
难度:简单
| 相关标签:树、深度优先搜索、字符串、回溯、二叉树
-
题目: 给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。 -
思路: 从根节点到叶子的路径,所以需要前序遍历,这样才方便让父节点指向孩子节点,找到对应的路径
-
注意:
-
代码:
- 反思:
Leetcode404.左叶子之和
难度:简单
| 相关标签:树、深度优先搜索、广度优先搜索、二叉树
-
题目: 给定二叉树的根节点 root ,返回所有左叶子之和。
-
思路:
-
注意:
- 左叶子的定义:节点A的左孩子不为空,且左孩子的左右孩子都为空(说明是叶子节点),那么A节点的左孩子为左叶子节点
-
代码:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null){
return 0;
}
int leftValue = sumOfLeftLeaves(root.left); // 左
int rightValue = sumOfLeftLeaves(root.right); // 右
int midValue = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
midValue = root.left.val;
}
int sum = midValue + leftValue + rightValue; // 中
return sum;
}
}
- 反思:
Leetcode222.完全二叉树的节点个数
难度:简单
| 相关标签:位运算、树、二分查找、二叉树
-
题目: 给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。 -
思路:
-
注意:
- 完全二叉树也是二叉树,所以可以直接用二叉树遍历方法统计结点数
- 也可以通过完全二叉树的特性:结点数=2^h - 1 h是高度
-
代码:
class Solution {
//满二叉树的结点数为:2^depth - 1
public int countNodes(TreeNode root) {
if (root == null){
return 0;
}
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 0, rightDepth = 0; // 这里初始为0是有目的的,为了下面求指数方便
while (left != null) { // 求左子树深度
left = left.left;
leftDepth++;
}
while (right != null) { // 求右子树深度
right = right.right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
- 反思: