110. 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
标签:right,res,二叉树,深度,null,root,104,left From: https://www.cnblogs.com/libertylhy/p/17225599.html一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
算法
如何判断以当前传入节点为根节点的二叉树是否是平衡二叉树呢?当然是其左子树高度和其右子树高度的差值。
分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则返回-1,表示已经不是二叉平衡树了。
1 class Solution { 2 private int height(TreeNode root) { 3 if (root == null) return 0; 4 int left = height(root.left); 5 int right = height(root.right); 6 if (left == -1 || right == -1 || Math.abs(left - right) > 1) { 7 return -1; 8 } 9 10 return Math.max(left, right) + 1; 11 12 } 13 public boolean isBalanced(TreeNode root) { 14 return height(root) != -1; 15 } 16 }257. 二叉树的所有路径
给你一个二叉树的根节点
root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。叶子节点 是指没有子节点的节点。
/** * 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, paths, res); return res; } private void traversal(TreeNode root, List<Integer> paths , List<String> res ) { 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, paths, res); paths.remove(paths.size() - 1); } if (root.right != null) { traversal(root.right, paths, res); paths.remove(paths.size() - 1); } } }
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if (root == null) { return res; } helper(root, String.valueOf(root.val), res); return res; } private void helper(TreeNode root, String path, List<String> res) { if (root == null) { return; } if (root.left == null && root.right == null) { res.add(path); return; } if (root.left != null) { helper(root.left, path + "->" + String.valueOf(root.left.val), res); } if (root.right != null) { helper(root.right, path + "->" + String.valueOf(root.right.val), res); } } }
404. 左叶子之和
给定二叉树的根节点root
,返回所有左叶子之和。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; } }