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;
}
private int getHight(TreeNode root){
if(root == null ){
return 0;
}
//如果当前节点为null,则返回高度0。
递归计算左子树的高度leftHeight,如果返回值为-1,则说明左子树不是平衡的,直接返回-1。
递归计算右子树的高度rightHeight,如果返回值为-1,则说明右子树不是平衡的,直接返回-1。
如果左子树高度和右子树高度的绝对值大于1,则说明当前节点不是平衡的,返回-1。
否则,返回左子树高度和右子树高度中的较大值加1,表示当前节点的高度。
int leftHeight = getHight(root.left);
if(leftHeight==-1){
return -1;
}
int rightHeight = getHight(root.right);
if(rightHeight==-1){
return -1;
}
if(Math.abs(leftHeight-rightHeight)>1){
return -1;
}
return Math.max(leftHeight,rightHeight)+1;
}
}
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 List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
constructPaths(root,"",paths);
return paths;
}
public void constructPaths(TreeNode root, String path, List<String> paths){
if(root != null ){
StringBuffer pathSB = new StringBuffer(path);
pathSB.append(Integer.toString(root.val));
// 当前节点是叶子节点
if(root.left ==null && root.right == null){
// 把路径加入到答案中
paths.add(pathSB.toString());
}else{
pathSB.append("->"); // 当前节点不是叶子节点,继续递归遍历
constructPaths(root.left, pathSB.toString(), paths);
constructPaths(root.right, pathSB.toString(), paths);
}
}
}
}
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 {
int result = 0;
public int sumOfLeftLeaves(TreeNode root) {
dfs(root,false);
return result;
}
private void dfs(TreeNode node, boolean isLeft) {
if(node == null ){
return;
}
if(node.left == null && node.right == null && isLeft){
result += node.val;
}
dfs(node.left, true);
dfs(node.right, false);
}
}