leetCode104.MaximumDepthofBinaryTree二叉树问题

104. Maximum Depth of Binary Tree

创新互联从2013年创立,先为河源等服务建站,河源等地企业,进行企业商务咨询服务。为河源企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

同Minimum Depth of Binary Tree求解类似。 http://qiaopeng688.blog.51cto.com/3572484/1835237 

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        int iMaxDepth = 0;
        vector depths;
        stack s;
        
        TreeNode *p,*q;
        q = NULL;
        p = root;
        if(!root)
            return 0;
        while(p != NULL || s.size() > 0)
        {
            while( p != NULL)
            {
                s.push(p);
                p = p->left;
            }
            if(s.size() > 0)
            {
                p = s.top();
                 
                if( NULL == p->left && NULL == p->right)
                {
                    if(iMaxDepth < s.size())
                        iMaxDepth = s.size();
                }
                 
                if( (NULL == p->right || p->right == q) )
                {
                    q = p;
                    s.pop();
                    p = NULL;
                }
                else
                    p = p->right;
            }
        }
        return iMaxDepth;
    }
};

分享文章:leetCode104.MaximumDepthofBinaryTree二叉树问题
URL标题:http://hxwzsj.com/article/ggjdij.html

其他资讯

Copyright © 2025 青羊区翔捷宏鑫字牌设计制作工作室(个体工商户) All Rights Reserved 蜀ICP备2025123194号-14
友情链接: 营销网站建设 企业网站建设公司 响应式网站建设 网站建设费用 企业网站设计 网站制作 成都网站建设 网站建设 成都营销网站制作 广安网站设计 定制网站建设多少钱 成都网站制作 外贸营销网站建设 重庆网站制作 手机网站设计 成都网站建设 营销型网站建设 手机网站制作 成都网站建设公司 营销型网站建设 成都网站建设 成都网站设计