数的高度 java,java – 获取没有函数参数的二叉树的高度

import java.util.Scanner;

public class BinaryTree {

private int info;

private BinaryTree left;

private BinaryTree right;

private int height = 1;

public BinaryTree()

{

left = null;

right = null;

}

public BinaryTree(int theInfo)

{

Scanner sc = new Scanner(System.in);

int intNum;

String s;

info = theInfo;

System.out.print("Does the node " + info + " have a left child (y or n)? ");

s = sc.next();

if (s.equals("y"))

{

System.out.print ("What value should go in the left child node? ");

intNum = sc.nextInt();

left = new BinaryTree(intNum);

}

System.out.print("Does the node " + info + " have a right child (y or n)? ");

s = sc.next();

if (s.equals("y"))

{

System.out.print ("What value should go in the right child node? ");

intNum = sc.nextInt();

right = new BinaryTree(intNum);

}

}

int heightLeft = 0;

int heightRight = 0;

public int getHeight()

{

int counterOld = 0;

int counter = 0;

if (left != null)

{

counter++;

if (counter > counterOld)

{

counterOld = counter;

}

counter += left.getHeight();

}

if (left == null)

{ System.out.println("counter is: " + counter + " and counterOld is: " + counterOld);

/*if (counter > counterOld)

{

counterOld = counter;

} */

counter = 0;

}

if (right != null)

{

counter++;

if (counter > counterOld)

{

counterOld = counter;

}

counter += right.getHeight();

}

if (right == null)

{ System.out.println("counter is" + counter + " and counterOld is: " + counterOld);

/*if (counter > counterOld)

{

counterOld = counter;

} */

counter = 0;

}

return counterOld;

}

}

import java.util.Scanner;

public class BinaryTester {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

BinaryTree myTree;

Scanner sc = new Scanner(System.in);

int intNum;

System.out.print("What value should go in the root? ");

intNum = sc.nextInt();

myTree = new BinaryTree(intNum);

System.out.println("Height is " + myTree.getHeight());

}

}

400

/

300

/

200

/

100

我用树高函数计数器得到了混合结果.我想根据最低节点计算树的下降程度.例如,上面的树应该是3的高度,根被计为0.我得到高度不正确的结果1.如果我输入如下的树,我得到正确的结果:

400

/ \

300 10

/ / \

100 4 5

/

3

这棵树给我3的高度,这正是我所寻找的.任何人都知道如何调整我的代码来解释所有树木?

解决方法:

使用树时,递归更容易.

public int getHeight(BinaryTree node){

if(node == null){

return 0;

}

int left = getHeight(node.left);

int right = getHeight(node.right);

return Math.max(left, right) + 1;

}

此方法提供一个基于高度.如果你想在零开始计数,那么你可以从中减去一个,例如

getHeight(tree) - 1

标签:java,data-structures

来源: https://codeday.me/bug/20190611/1221222.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值