码迷,mamicode.com
首页 > 编程语言 > 详细

Balanced Binary Tree(Java代码没过,什么原因???)

时间:2014-07-31 20:55:47      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:数据结构   算法   学习   

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.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode *root) {
        int depth=0;
        return isBalanced(root,&depth);
    }
    bool isBalanced(TreeNode *root,int* depth){
        if(root==NULL){
            *depth=0;
            return true;
        }
        
        int left,right;
        if(isBalanced(root->left,&left) && isBalanced(root->right,&right)){
            int diff=left-right;
            if(diff<=1 && diff>=-1){
                *depth=1+(left>right?left:right);
                return true;
            }
        }
        return false;
    }
    
};
同样思路的Java代码没过,谁能告诉我问题所在,因为参数的问题吗?
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        int depth=0;
        return isBalanced(root,depth);
    }
    public boolean isBalanced(TreeNode node,int depth){
        if(node == null){
            return true;
        } 
        int leftDepth=0,rightDepth=0;
        if( isBalanced(node.left,leftDepth) && isBalanced(node.right,rightDepth) ){
            int diff=leftDepth-rightDepth;
            if(diff<=1 && diff>=-1){
                depth=1+((leftDepth>rightDepth)?(leftDepth):(rightDepth));
                return true;
            }
        }
        return false;
    }
}


Balanced Binary Tree(Java代码没过,什么原因???),布布扣,bubuko.com

Balanced Binary Tree(Java代码没过,什么原因???)

标签:数据结构   算法   学习   

原文地址:http://blog.csdn.net/dutsoft/article/details/38321635

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!