函数接口定义:
int GetHeight( BinTree BT );
其中BinTree结构定义如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
要求函数返回给定二叉树BT的高度值。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree(); /* 实现细节忽略 */
int GetHeight( BinTree BT );
int main()
{
BinTree BT = CreatBinTree();
printf("%d\n", GetHeight(BT));
return 0;
}
/* 你的代码将被嵌在这里 */
函数解决:
方法一:递归
自顶向下递归:每向下递归一次就加1
int GetHeight( BinTree BT ){
if(BT==NULL)return 0;
int x,y;
x=GetHeight(BT->Left)+1;
y=GetHeight(BT->Right)+1;
return x>y?x:y;
}
自底向上递归:每次向上则比较左右子树的深度加1
int GetHeight( BinTree BT ){
if(BT==NULL)return 0;
int x,y;
x=GetHeight(BT->Left);
y=GetHeight(BT->Right);
return max(x,y)+1;//取左右子树中较大高度数返回
}
非递归算法(Java描述)
方法二:后序遍历二叉树
思路:按后序遍历二叉树,节点最大栈长即为二叉树的高度。
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null){
return 0;
}
int height=0;
Stack<TreeNode> nodes=new Stack<>();
Stack<Integer> tag=new Stack<>();
while(root!=null||!nodes.isEmpty()){
while(root!=null){
nodes.push(root);
tag.push(0);
root=root.left;
}
if(tag.peek()==1){
height=Math.max(height, nodes.size());
nodes.pop();
tag.pop();
root=null;
}else{
root=nodes.peek();
root=root.right;
tag.pop();
tag.push(1);
}
}
return height;
}
}
方法三:按层次遍历二叉树
思路:按层次遍历二叉树,使用队列。
public class Solution {
static class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int value){
this.val=value;
}
}
public static int getHeight(TreeNode root){
if(root==null){
return 0;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
int height=1;
while(!queue.isEmpty()){
TreeNode node=queue.peek();
if(node.left==null&&node.right==null){
break;
}else{
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
queue.poll();
height++;
}
}
return height;
}
}