LeetCode:110.平衡二叉树
问题描述
解决方案一:自底向下递归【类似于前序遍历的顺序】
1.思路
2.代码实现
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
} else {
return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
}
public int height(TreeNode root) {
if (root == null) {
return 0;
} else {
return Math.max(height(root.left), height(root.right)) + 1;
}
}
}
3.复杂度分析

解决方案二:自底向上递归【类似于后序遍历的顺序】
1.思路
2.代码实现
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
public int height(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
3.复杂度分析

LeetCode:257. 二叉树的所有路径
问题描述
解决方案:
1.思路:
- 使用深度优先搜索。在深度优先搜索遍历二叉树时,我们需要考虑当前的节点以及它的孩子节点。
- 如果当前节点不是叶子节点,则在当前的路径末尾添加该节点,并继续递归遍历该节点的每一个孩子节点。
- 如果当前节点是叶子节点,则在当前路径末尾添加该节点后我们就得到了一条从根节点到叶子节点的路径,将该路径加入到答案即可。
2.代码实现
class Solution {
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);
}
}
}
}
3.复杂度分析

LeetCode:404.左叶子之和
问题描述
解决方案:
1.思路:
- 递归逻辑是:如果左节点不为空,并且左节点的左右孩子为空,那么就符号条件,加入和即可;
2.代码实现
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
help(root);
return sum;
}
public void help(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
help(root.left);
help(root.right);
}
}
3.复杂度分析
