# 小算法：求一棵二叉树的高度以及求一个节点的左右子树的高度

## 求一棵二叉树的高度以及求一个节点的左右子树的高度

public int height() {
return Math.max(left==null?0:left.height(),right==null?0:right.height())+1;
}


//返回左子树的高度
public int leftHeight() {
if(left==null) {
return 0;
}
return left.height();
}


//返回左子树的右高度
public int rightHeight() {
if(right==null) {
return 0;
}
return right.height();
}


package Day05;

public class TreeHeight {
public static void main(String[] args) {
BinaryTree binaryTree=new BinaryTree();
Node n4=new Node(4);
Node n3=new Node(3);
Node n6=new Node(6);
Node n5=new Node(5);
Node n7=new Node(7);
Node n8=new Node(8);
binaryTree.setRoot(n4);
n4.setLeft(n3);
n4.setRight(n6);
n6.setLeft(n5);
n6.setRight(n7);
n7.setRight(n8);

System.out.println("树的总高度:"+binaryTree.height());
System.out.println("节点4的左子树高度："+n4.leftHeight());
System.out.println("节点4的右子树高度："+n4.rightHeight());
}
}
class BinaryTree{
Node root;
public void setRoot(Node root) {
this.root=root;
}

public int height() {
if(root==null) {
return 0;
}else {
return root.height();
}
}
}
class Node{
int value;
Node left;
Node right;
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public Node(int value) {
this.value = value;
}

public int height() {
return Math.max(left==null?0:left.height(),right==null?0:right.height())+1;
}
//返回左子树的高度
public int leftHeight() {
if(left==null) {
return 0;
}
return left.height();
}
//返回左子树的右高度
public int rightHeight() {
if(right==null) {
return 0;
}
return right.height();
}
}


01-16 298

11-16 5万+
04-03 1万+
02-10 2万+
04-10 2253
03-20 3276
03-26 264
05-24 2万+
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客