leetCode 104. Maximum Depth of Binary Tree 二叉树问题
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
代码如下:
/***Definitionforabinarytreenode.*structTreeNode{*intval;*TreeNode*left;*TreeNode*right;*TreeNode(intx):val(x),left(NULL),right(NULL){}*};*/classSolution{public:intmaxDepth(TreeNode*root){intiMaxDepth=0;vector<int>depths;stack<TreeNode*>s;TreeNode*p,*q;q=NULL;p=root;if(!root)return0;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;}elsep=p->right;}}returniMaxDepth;}};
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。