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 int getHeight(TreeNode root){
//若遍历到空结点,说明为最小高度0
if(root == null){
return 0;
}
//递归求左子树高度
int leftHeight = getHeight(root.left);
//该分支之前已经有非平衡子树
if(leftHeight == -1){
return -1;
}
//递归求右子树高度
int rightHeight = getHeight(root.right);
//该分支之前已经有非平衡子树
if(rightHeight == -1){
return -1;
}
//左右子树高度差大于1,第一次遇见非平衡树,return -1;
if(Math.abs(leftHeight - rightHeight) > 1){
return -1;
}
//正常情况
return Math.max(leftHeight, rightHeight) + 1;
}
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -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> result = new ArrayList<>();
if(root == null){
return result;
}
List<Integer> paths = new ArrayList<>();
traversal(root, paths, result);
return result;
}
public void traversal(TreeNode root, List<Integer> paths, List<String> result){
//中序中的中
paths.add(root.val);
//中序的左
if(root.left != null){
//递归,加入左结点元素
traversal(root.left, paths, result);
//回溯,路径中弹出最后一个元素
paths.remove(paths.size() - 1);
}
//中序的右
if(root.right != null){
traversal(root.right, paths, result);
paths.remove(paths.size() - 1);
}
//如果走到叶子结点,说明这条路走到底,将path中的路径进行处理并返回上一级
if(root.left == null && root.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));
//箭头处理结束,转为字符串
result.add(sb.toString());
//该条路径处理结束,返回继续下一条路径的回溯
return;
}
}
}
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;
}
//左分支递归
int leftValue = sumOfLeftLeaves(root.left);
//右分支递归
int rightValue = sumOfLeftLeaves(root.right);
int midValue = 0;
//核心判断逻辑,以父结点为基础判断当前结点是否为左叶子结点
if(root.left != null && root.left.left == null && root.left.right == null){
midValue = root.left.val;
}
//中处理,对所有情况进行加和
int sum = midValue + leftValue + rightValue;
return sum;
}
}