溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

leetCode 104. Maximum Depth of Binary Tree 二叉樹問題

發(fā)布時(shí)間:2020-07-04 08:54:18 來源:網(wǎng)絡(luò) 閱讀:427 作者:313119992 欄目:編程語言

104. Maximum Depth of Binary Tree


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<int> depths;
        stack<TreeNode *> 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;
    }
};


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI