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 getHight(root) != -1;
}
public int getHight(TreeNode root){
if(root == null){
return 0;
}
int leftHeight = getHight(root.left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = getHight(root.right);
if (rightHeight == -1) {
return -1;
}
// 左右子树高度差大于1,return -1表示已经不是平衡树了
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
}
257. 二叉树的所有路径
题解及想法
需要用到回溯法,还不太熟练,特别要注意中序遍历的中药在条件判断之前,否则该节点就没有保存到paths中,因为在本题中,条件判断后有return,会直接结束该层循环。
/**
* 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<>(); //最后结果
if(root == null) return res;
List<Integer> paths = new ArrayList<>(); //存放中间路径
traversal(root,res,paths);
return res;
}
private void traversal(TreeNode root,List<String> res,List<Integer> paths){
paths.add(root.val); //中序遍历的中
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)); //拼接最后一个节点
res.add(sb.toString());
return;
}
if(root.left != null){ //中序遍历的左
traversal(root.left,res,paths);
paths.remove(paths.size() - 1); //回溯
}
if(root.right != null){ //中序遍历的右
traversal(root.right,res,paths);
paths.remove(paths.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 midValue = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
midValue = root.left.val;
}
int leftValue = sumOfLeftLeaves(root.left); // 左
int rightValue = sumOfLeftLeaves(root.right); // 右
int sum = midValue + leftValue + rightValue; // 中
return sum;
}
}