110.平衡二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return balance(root) != -1;
}
public int balance(TreeNode node) {
if (node == null) {
return 0;
}
int d1 = balance(node.left);
if (d1 == -1) {
return -1;
}
int d2 = balance(node.right);
if (d2 == -1) {
return -1;
}
if (Math.abs(d1 - d2) > 1) {
return -1;
}
return Math.max(d1, d2) + 1;
}
}
257. 二叉树的所有路径
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
if (root != null) {
traPath(res, path, root);
}
return res;
}
public void traPath(List<String> res, List<Integer> path, TreeNode node) {
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("->");
}
sb.append(path.get(path.size() - 1));
res.add(sb.toString());
return;
}
if (node.left != null) {
traPath(res, path, node.left);
path.remove(path.size() - 1);
}
if (node.right != null) {
traPath(res, path, node.right);
path.remove(path.size() - 1);
}
}
}
404.左叶子之和
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 0;
}
int leftValue = sumOfLeftLeaves(root.left);
if (root.left != null && root.left.left == null && root.left.right == null) {
leftValue = root.left.val;
}
int rightValue = sumOfLeftLeaves(root.right);
int sum = leftValue + rightValue;
return sum;
}
}
222.完全二叉树的节点个数
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int leftValue = countNodes(root.left);
int rightValue = countNodes(root.right);
return leftValue + rightValue + 1;
}
}