您的位置:首页 > Web前端

剑指offer 6.3 知识迁移能力2- 二叉树的深度

2014-08-11 15:44 387 查看
面试题39: 二叉树的深度

题目:输入一棵二元树的根结点,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

例如:输入二元树:

10

/ \

6 14

/ / \

4 12 16

输出该树的深度3。

二叉树的结点定义如下:

struct SBinaryTreeNode // a node
of the binary tree

{

int m_nValue; // value of node

SBinaryTreeNode *m_pLeft; // left child of node

SBinaryTreeNode *m_pRight; // right child of node

};
分析:题目中定义的树的深度,也就是最长路径。

如果树中只有一个节点,深度为1,。

如果根节点只有左子树没有右子树,那么树的深度为 左子树深度+1;同样只有右子树没有左子树,深度为 右子树深度+1;

如果既有左子树也有右子树,那么树的深度为左、右子树深度的较大值 + 1;

这个思路,可以用递归实现。

int TreeDepth(SBinaryTreeNode *pTreeNode)
{
// the depth of a empty tree is 0
if(!pTreeNode)
return 0;

// the depth of left sub-tree
int nLeft = TreeDepth(pTreeNode->m_pLeft);
// the depth of right sub-tree
int nRight = TreeDepth(pTreeNode->m_pRight);

// depth is the binary tree
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: