您的位置:首页 > 其它

leetcode Maximum Depth of Binary Tree

2015-06-04 17:40 288 查看
解题思路:

深度优先遍历二叉树,

先遍历左孩子,一直到叶子节点,然后回溯,用栈来回溯,遍历右孩子。用栈表示哪些节点有被访问过。

/**
* 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 depth = 0;
int max_depth = 0;
stack<TreeNode*> nodes;
set<TreeNode*> visited_nodes;
if(root == NULL)
return 0;
nodes.push(root);
depth++;
visited_nodes.insert(root);
while(true){
if(root == NULL)
return max_depth;
if((root->left != NULL)&&(visited_nodes.find(root->left)==visited_nodes.end())){
nodes.push(root->left);
visited_nodes.insert(root->left);
root = root->left;
depth++;
}
else if((root->right != NULL)&&(visited_nodes.find(root->right)==visited_nodes.end())){
nodes.push(root->right);
visited_nodes.insert(root->right);
root = root->right;
depth++;
}
else{
if((root->right == NULL)&&(root->left) == NULL){
if(depth >= max_depth)
max_depth = depth;
}
if(nodes.empty()){
return max_depth;
}
nodes.pop();
if(nodes.empty())
return max_depth;
root = nodes.top();
depth--;
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: