微软100题(52)求二叉树的深度

来源:互联网 发布:荷塘月色淘宝卖家论坛 编辑:程序博客网 时间:2024/06/01 08:17

题目:输入一棵二元树的根结点,求该树的深度。

从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

例如:输入二元树:
                                            10
                                          /     /
                                        6        14
                                      /         /   /
                                    4         12     16

输出该树的深度3。

二元树的结点定义如下:

struct BinaryTreeNode // a node of the binary tree
{
      int               m_nValue; // value of node
      BinaryTreeNode  *m_pLeft;  // left child of node
      BinaryTreeNode  *m_pRight; // right child of node
};


int BinaryTreeDepth(BinaryTreeNode* root){if(root==NULL) return 0;int leftdepth = BinaryTreeDepth(root->m_left);int rightdepth = BinaryTreeDepth(root->m_right);return (leftdepth>rightdepth)?(leftdepth+1):(rightdepth+1);}


0 0
原创粉丝点击