大纲
第六章 二叉树part04
大纲
● 110.平衡二叉树
● 257. 二叉树的所有路径
● 404.左叶子之和
leetcode 110
平衡二叉树
思路
细节
代码
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
if (Math.abs(getDepth(root.left) - getDepth(root.right)) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
public int getDepth(TreeNode node) {
if (node == null) return 0;
return 1 + Math.max(getDepth(node.left), getDepth(node.right));
}
}
复杂度
- 时间
O(n)
- 空间
O(n)
leetcode 257
二叉树的所有路径
思路
细节
代码
class Solution {
List<Integer> paths = new ArrayList<>();
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) return res;
dfs(root);
return res;
}
public void dfs(TreeNode node) {
paths.add(node.val);
if (node.left == null && node.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < paths.size() - 1; i++) sb.append(paths.get(i)).append("->");
sb.append(paths.get(paths.size() - 1));
res.add(sb.toString());
return;
}
if (node.left != null) {
dfs(node.left);
paths.remove(paths.size() - 1);
}
if (node.right != null) {
dfs(node.right);
paths.remove(paths.size() - 1);
}
}
}
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
Stack<Object> stack = new Stack<>();
stack.push(root);
stack.push(root.val + "");
while (!stack.isEmpty()) {
String path = (String) stack.pop();
TreeNode node = (TreeNode) stack.pop();
if (node.left == null && node.right == null) res.add(path);
if (node.right != null) {
stack.push(node.right);
stack.push(path + "->" + node.right.val);
}
if (node.left != null) {
stack.push(node.left);
stack.push(path + "->" + node.left.val);
}
}
return res;
}
}
复杂度
- 时间
O(n)
- 空间
O(n)
leetcode 404
左叶子之和
思路
- 你华1A秒了
细节
代码
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
return (root.left != null && root.left.left == null && root.left.right == null ? root.left.val : 0) + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}
}
复杂度
- 时间
O(n)
- 空间
O(n)