leetcode Maximum Depth of Binary Tree

来源:互联网 发布:开淘宝店的 编辑:程序博客网 时间:2024/06/06 15:43

解题思路:

深度优先遍历二叉树,

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

/** * 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--;                                                                         }                                                                                }        }};


0 0
原创粉丝点击