您的位置:首页 > 其它

Maximum Depth of Binary Tree [LEETCODE]

2013-09-25 10:33 337 查看
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.

===========================================================================

Aparently, recursive solution came into my mind as soon as I've finished reading the problem. Here's the code:

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

//Recursive Solution:
//There's 2 conditions:
//1 root is NULL, break point, should return 0 as its depth
//2 root is not NULL, should return its max child depth plus 1
20     if(NULL == root){
return 0;
}
return std::max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};


----------------------------------------------------------------------

But I wondered if there's a non-recursive solution. So I use a stack to store the traverse path. Additionally, I used a pair to store node status, which indicated if current node's children have been visited or not. here's the code:

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(NULL == root){
return 0;
}
int max_depth = 0;

//node status 0:  neither left nor right has been visited
//node status 1:  only left has been visited
//node status 2:  left and right all have been visited
stack<pair<TreeNode *,int> > s;
//push root into stack, initail status is 0, because both children haven't been visited.
s.push(make_pair(root,0));
pair<TreeNode *, int>* p_pair;
while(!s.empty()){
//fetch the top node in stack
p_pair = &(s.top());

//neither left nor right has been visited
//visit left child, then set the status code to 1
if(p_pair->second == 0) {
if(NULL != p_pair->first->left){
s.push(make_pair(p_pair->first->left,0));
}
p_pair->second = 1;
}

//only left has been visited,
//visit right child, then set the status code to 2
else if(p_pair->second == 1) {
if(NULL != p_pair->first->right){
s.push(make_pair(p_pair->first->right,0));
}
p_pair->second = 2;
}

//left and right all have been visited
//pop this node out of stack. and do nothing.
else if(p_pair->second == 2) {
s.pop();
}

//current node's depth is equal to the size of stack
max_depth = max((int)(s.size()), max_depth);
}

return max_depth;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: