注:最近忙着实验!!!只能只写代码了!!!
110. 平衡二叉树
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) == -1 ? false : true;
}
public int getHeight(TreeNode node) {
if (node == null) return 0;
int leftDepth = getHeight(node.left);
if (leftDepth == -1) return -1;
int rightDepth = getHeight(node.right);
if (rightDepth == -1) return -1;
return Math.abs(leftDepth - rightDepth) > 1 ? -1 : 1 + Math.max(leftDepth, rightDepth);
}
}
257. 二叉树的所有路径
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new LinkedList<>();
List<Integer> path = new LinkedList<>();
if (root == null) return res;
traversal(root, path, res);
return res;
}
void traversal (TreeNode cur, List<Integer> path, List<String> res) {
path.add(cur.val);
if (cur.left == null && cur.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));
res.add(sb.toString());
return;
}
if (cur.left != null) {
traversal(cur.left, path, res);
path.remove(path.size() - 1);
}
if (cur.right != null) {
traversal(cur.right, path, res);
path.remove(path.size() - 1);
}
}
}
404. 左叶子之和
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
Deque<TreeNode> que = new LinkedList<>();
int sum = 0;
que.offer(root);
while (!que.isEmpty()) {
TreeNode node = que.poll();
if (node.left != null && node.left.left == null && node.left.right == null) {
sum += node.left.val;
}
if (node.left != null) que.offer(node.left);
if (node.right != null) que.offer(node.right);
}
return sum;
}
}