LintCode - Maximum Depth of Binary Tree

解法一 recursion

divide and conquer

class Solution {
public:
    int maxDepth(TreeNode * root) {
        if(!root) return 0;
        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        return max(left, right)+1;
    }
};

traverse

class Solution {
public:
    int res;
    int maxDepth(TreeNode * root) {
        res=0;
        helper(root, 0);
        return res;
    }
    void helper(TreeNode* root, int temp){
        res = max(temp, res);
        if(!root) return;
        helper(root->left, temp+1);
        helper(root->right, temp+1);
    }
};

解法二 non-recursion

class Solution {
public:
    int maxDepth(TreeNode * root) {\
        int res=0;
        queue<TreeNode*> st;
        if(!root) return res;
        st.push(root);
        while(!st.empty()){
            int n = st.size();
            for(int i=0;i<n;i++){
                TreeNode* t = st.front(); st.pop();
                if(t->right) st.push(t->right);
                if(t->left) st.push(t->left);
            }
            res++;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/83994864
今日推荐