Balanced Binary Tree - LeetCode

来源:互联网 发布:蒙大拿级战列舰数据 编辑:程序博客网 时间:2024/05/01 19:33

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

这道题很简单,但是一定要注意随时return!!!

代码已AC,如下:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int height(TreeNode root){int h = 1;if(root == null){return h;}else {int i = height(root.left);int j = height(root.right);if(i>j)return (h+i);elsereturn (h+j);}    }    public boolean isBalanced(TreeNode root) {if(root == null){return true;}else {int i = height(root.left);int j = height(root.right);//System.out.println(i);//System.out.println(j);if(i - j >= 2)return false;else if(j - i >= 2)return false;else{boolean l = isBalanced(root.left);if(l == false)return l;boolean r = isBalanced(root.right);if(r == false)return r;}}return true;}}


0 0
原创粉丝点击