class Solution {
private Integer depth;
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
if (Math.abs(height(root.left) - height(root.right)) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(height(root.left), height(root.right)) + 1;
}
}
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root == null) {
return result;
}
dfs(root, new ArrayList<>(), result);
return result;
}
private void dfs(TreeNode node, List<Integer> path, List<String> result) {
path.add(node.val);
if (node.left == null && node.right == null) {
result.add(convertPath(path));
} else {
if (node.left != null) {
dfs(node.left, path, result);
path.remove(path.size() - 1);
}
if (node.right != null) {
dfs(node.right, path, result);
path.remove(path.size() - 1);
}
}
}
private String convertPath(List<Integer> list) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
if (i < list.size() - 1) {
sb.append("->");
}
}
return sb.toString();
}
}
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
int ans = 0;
if (root == null) {
return 0;
}
if (root.left != null && root.left.left == null && root.left.right == null) {
ans += root.left.val;
}
ans += sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
return ans;
}
}
public int countNodes(TreeNode root) {
if (root == null){
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}