Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 二叉树的深度

输入一棵二叉树的根结点,求该树的深度,从根结点到叶结点依次经过的结点(含根,叶结点)形成树的一条路径,最长路径的长度为树的深度#include <iostream>
using namespace std;struct BinaryTreeNode
{
 int data;
 struct BinaryTreeNode *lchild;
 struct BinaryTreeNode *rchild;
};typedef struct BinaryTreeNode BinTreeNode;//先序构造二叉树
BinTreeNode* preOrderCreateTree(BinTreeNode *head)
{
 int tmp;
 cin >> tmp;
 if (tmp == 0)
  head = NULL;
 else
 {
  head = new BinTreeNode;
  head->data = tmp;
  head->lchild = preOrderCreateTree(head->lchild);
  head->rchild = preOrderCreateTree(head->rchild);
 }
 
 return head;
}//先序遍历二叉树
void preVisitTree(const BinTreeNode *head)
{
 if (head == NULL)
  return;
 
 cout << head->data;
 preVisitTree(head->lchild);
 preVisitTree(head->rchild);
}void freeTree(BinTreeNode *head)
{
 if (head == NULL)
  return;
 
 freeTree(head->lchild);
 freeTree(head->rchild);
 delete head;
}int getTreeDeep(const BinTreeNode *head)
{
 if (head == NULL)
  return 0;
 int lDeep = getTreeDeep(head->lchild);
 int rDeep = getTreeDeep(head->rchild);
 return (lDeep > rDeep)?lDeep+1:rDeep+1;
}int main()
{
 BinTreeNode *root = preOrderCreateTree(root);
 if (root)
  cout << "deep: " << getTreeDeep(root) << endl;
 freeTree(root); 
 return 0;
}二叉树的常见问题及其解决程序 http://www.linuxidc.com/Linux/2013-04/83661.htm【递归】二叉树的先序建立及遍历 http://www.linuxidc.com/Linux/2012-12/75608.htm在JAVA中实现的二叉树结构 http://www.linuxidc.com/Linux/2008-12/17690.htm【非递归】二叉树的建立及遍历 http://www.linuxidc.com/Linux/2012-12/75607.htm二叉树递归实现与二重指针 http://www.linuxidc.com/Linux/2013-07/87373.htm二叉树先序中序非递归算法 http://www.linuxidc.com/Linux/2014-06/102935.htm轻松搞定面试中的二叉树题目 http://www.linuxidc.com/linux/2014-07/104857.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-09/106591.htm