二叉树高度-递归方式
程序代码获取二叉树高度。
package com.ginko.datastructure;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;/*** 二叉树*/
public class BinaryTree {private BinaryTreeNode root;//根节点public BinaryTree(BinaryTreeNode root) {this.root = root;}/*** 二叉树层序遍历* 核心:引入队列,从root开始,左右孩子分别入队,然后从队列追个出队,队列为空时,遍历结束*/public List levelOrder() {List levelOrderResult = new ArrayList();//保持层序遍历的结果Queue queue = new LinkedList();queue.add(root);//加入根节点while (!queue.isEmpty()) {BinaryTreeNode currentNode = (BinaryTreeNode)queue.remove();//从队列获取levelOrderResult.add(currentNode.getData());BinaryTreeNode left = currentNode.getLeft();BinaryTreeNode right = currentNode.getRight();if(left != null) {queue.add(left);}if(right != null) {queue.add(right);}}return levelOrderResult;}/*** 获取二叉树高度* @param root* @return*/public int getTreeHeight(BinaryTreeNode root) {if(root == null) {return 0;}int leftHeight = getTreeHeight(root.getLeft());int rightHeight = getTreeHeight(root.getRight());return leftHeight > rightHeight? leftHeight +1:rightHeight + 1;}public static void main(String[] args) {/*** 构造树* 1* 2 3* 4 5 6 7* 8 9*/BinaryTreeNode node8 = new BinaryTreeNode(8,null,null);BinaryTreeNode node9 = new BinaryTreeNode(9,null,null);BinaryTreeNode node4 = new BinaryTreeNode(4,node8,node9);BinaryTreeNode node5 = new BinaryTreeNode(5,null,null);BinaryTreeNode node2 = new BinaryTreeNode(2,node4,node5);BinaryTreeNode node6 = new BinaryTreeNode(6,null,null);BinaryTreeNode node7 = new BinaryTreeNode(7,null,null);BinaryTreeNode node3 = new BinaryTreeNode(3,node6,node7);BinaryTreeNode node1 = new BinaryTreeNode(1,node2,node3);BinaryTree binaryTree = new BinaryTree(node1);List result = binaryTree.levelOrder();result.forEach(s->{System.out.print(s + ",");});System.out.println();int height = binaryTree.getTreeHeight(node1);System.out.println("二叉树高度为:" + height);}
}
运行结果如下,符合预期。