您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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; } };
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。