二叉树的深度

一般二叉树的算法很容易地想到使用递归。

在求一棵二叉树的深度时,我们判断根结点,如果根节点存在,则可以将问题转换成:求该根节点的左右子树中深度较大者+1。
代码如下:

class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        int leftDepth, rightDepth;
        if(pRoot == NULL) return 0;
        else
        {
            leftDepth = TreeDepth(pRoot->left);
            rightDepth = TreeDepth(pRoot->right);
            return leftDepth > rightDepth? leftDepth + 1:rightDepth + 1;
        }
    }
};

你可能感兴趣的:(数据结构/算法)