Maximum Depth of Binary Tree

Q:

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.

A:

借用了一下后序遍历的方式,在左右子树全部遍历的情况下才对当前高度减1

烦躁的是,stack的实现应该是如果为空,调用top函数会返回异常,不过想想逻辑上的确应该如此,就是浪费了我很多时间去找bug,擦了。

class Solution {
public:
    int maxDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<TreeNode*> s;
        stack<bool> right;
        int path = 0;
        int h = 0;
        TreeNode* cur = root;
        while (cur || !s.empty()) {
            while (cur) {
                s.push(cur);
                right.push(false);
                cur = cur->left;
                ++path;
            }
            h = max(h, path);
            
            while (!right.empty() && right.top()) {
                right.pop();
                s.pop();
                --path;
            }
            if (!s.empty()) {
                TreeNode* top = s.top();
                cur = top->right;
                right.top() = true;
            }            
        }
        return h;
    }
};

 

posted @ 2013-06-16 22:53  dmthinker  阅读(95)  评论(0)    收藏  举报