package _06binary_tree.day17._01balanced_tree;
public class Solution {
public boolean isBalanced(TreeNode root) {
// 递归法
// != -1 true | == -1 false
return getHeight(root) != -1;
}
/**
* 递归:后序遍历
* @param node
* @return
*/
public static int getHeight(TreeNode node) {
if (node == null) return 0;
int leftHeight = getHeight(node.left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(node.right);
if (rightHeight == -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return 1 + Math.max(leftHeight, rightHeight);
}
}
package _06binary_tree.day17._02binary_tree_path;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Solution {
// 迭代:栈
public List<String> binaryTreePaths2(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
Stack<Object> stack = new Stack<>();
// 节点和路径入栈
stack.push(root);
stack.push(root.val + ""); // 方便转成String
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;
}
// 递归
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
List<Integer> path = new ArrayList<>();
traverse(root, path, res);
return res;
}
private void traverse(TreeNode node, List<Integer> path, List<String> res) {
path.add(node.val);
// 终止条件:节点为叶子节点
if (node.left == null && node.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size() - 1; i++) {
sb.append(path.get(i) + "->");
}
// 最后的节点
sb.append(path.get(path.size()));
// 将该路径加入res
res.add(sb.toString());
return;
}
// 左
if (node.left != null) {
traverse(node.left, path, res);
path.remove(path.size() - 1); // 回溯
}
// 右
if (node.right != null) {
traverse(node.right, path, res);
path.remove(path.size() - 1); // 回溯
}
}
}
package _06binary_tree.day17._03sum_of_leftleaves;
public class Solution {
// 递归
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int left = sumOfLeftLeaves(root.left);
if (root.left != null && root.left.left == null && root.left.right == null) {
left = root.left.val;
}
int right = sumOfLeftLeaves(root.right);
return left + right;
}
}