110. 平衡二叉树
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 getHeight(root) != -1;
}
public int getHeight(TreeNode root){
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;
}
if(Math.abs(leftHeight - rightHeight) > 1){
return -1;
}
else{
return Math.max(leftHeight , rightHeight) + 1;
}
}
}
257. 二叉树的所有路径
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) {
//使用递归法解决该问题
//创建一个string的List来存放结果
List<String> res = new ArrayList<>();
if(root == null){
return res;
}
//创建一个path来存放路径
List<Integer> path = new ArrayList<>();
travel(root,res,path);
return res;
}
public void travel(TreeNode root , List<String> res, List<Integer> path){
//实现递归调用
//首先确定传入的参数,其次确定终止条件,最后确定内部逻辑
//前序遍历
path.add(root.val);
//终止条件
if(root.left == null && root.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));
//此时path中则存在该条路劲
res.add(sb.toString());
return;
}
if(root.left != null){
travel(root.left,res,path);
//回溯
path.remove(path.size()-1);
}
if(root.right != null){
travel(root.right,res,path);
path.remove(path.size()-1);
}
}
}
404. 左叶子之和
404. 左叶子之和
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;
}
}