简体   繁体   English

平衡()二叉树

[英]balanced() binary tree

I need to write a method that determines whether a binary tree is balanced.我需要编写一个方法来确定二叉树是否平衡。 So first I'm going to have to determine the height of each side of the tree.所以首先我必须确定树每一边的高度。 But I'm having trouble understanding how I am going to count the max length of a subtree, without counting all the nodes in the subtree.但是我无法理解如何计算子树的最大长度,而不计算子树中的所有节点。 This question is very difficult to ask for me, so you guys can understand.这个问题对我来说很难问,所以你们可以理解。

// primary method
public int Height()
{
    int h = height( root );
}

// recursive method
private int height( Node x )
{
    if( x == null ) return 0;
    count++;                   
    height( x.left );
    height( x.right );
    return count;           
}

Here is my code for calculating the max height of the tree.这是我计算树的最大高度的代码。 But i dont know how to determine just the left or right sides' height, and this method seems to count the amount of nodes in the tree itself.但我不知道如何确定左侧或右侧的高度,这种方法似乎可以计算树本身的节点数量。

This method will not even compile, because of the return;这个方法甚至不会编译,因为return; statement - you need to return an int.声明 - 您需要返回一个 int。

So, if(x == null) , what should you return?那么, if(x == null) ,你应该返回什么? What is the height of an empty tree?一棵空树的高度是多少?

Once you have that figured out, imagine your root has only a left-subtree ( root.right == null ), and you know the height of the left-subtree.一旦你弄清楚了,想象你的根只有一个左子树( root.right == null ),你知道左子树的高度。 What should the height of the overall tree be?整棵树的高度应该是多少?

What if it has only a right subtree?如果它只有一个右子树怎么办?

Now, what if it has both?现在,如果两者兼而有之呢?

Note that you don't need a global counting variable for any of this.请注意,您不需要任何全局计数变量。

The height is 1 + max(left.height(), right.height()).高度为 1 + max(left.height(), right.height())。

You should return a value instead of setting a variable (count, in your case), otherwise you'll go mad.您应该返回一个值而不是设置一个变量(在您的情况下为计数),否则您会发疯的 go。

The height of a node is one more than the height of its tallest sub-node (hint: use Math.max ).节点的高度比其最高子节点的高度大一(提示:使用Math.max )。

Adding to the hints I'll also point out that you really want to use recursion.除了提示之外,我还要指出您确实想使用递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM