剑指 offer:38、二叉树的深度

2019-04-17  本文已影响0人  云中的Jason

38. 二叉树的深度

题目描述

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

解题思路:

解答:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
// 解法1:
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(!pRoot)
            return 0;
        return max(TreeDepth(pRoot->left) + 1, TreeDepth(pRoot->right) + 1);
    }
};
// 解法2:
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(!pRoot)
            return 0;
        queue<TreeNode *> que;
        que.push(pRoot);
        int depth = 0;
        while(!que.empty())
        {
            // 队列中每次迭代都只存储了一层的元素
            int size = que.size();
            depth++;
            for(int i = 0; i < size; ++i)
            {
                TreeNode *node = que.front();
                que.pop();
                if(node->left)
                    que.push(node->left);
                if(node->right)
                    que.push(node->right);
            }
        }
        return depth;
    }
};

大家有兴趣可以访问我的个人博客,不定时更新一些内容哦!

图片来自必应壁纸
上一篇 下一篇

猜你喜欢

热点阅读