【easy】104. Maximum Depth of Binary Tree 求二叉树的最大深度

求二叉树的最大深度

/**
 * 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 l,r;
        if (root == NULL) return 0;
        l = maxDepth(root->left);
        r = maxDepth(root->right);
        return max(l,r)+1;
        
        //一行代码的写法!!!!
        //return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
    }
};

非递归写法1(直接摘自其他博客):

int maxDepth(TreeNode *root)
{
    if (root == NULL) return 0;
    stack<TreeNode *> gray;
    stack<int> depth;
    int out = 0;

    gray.push(root);
    depth.push(1);
    while (!gray.empty()) {
        TreeNode *tmp = gray.top();
        int num = depth.top();
        gray.pop();
        depth.pop();
        if (tmp->left == NULL && tmp->right == NULL) {
            out = num > out ? num : out;
        }
        else {
            if (tmp->left != NULL) {
                gray.push(tmp->left);
                depth.push(num + 1);
            }
            if (tmp->right != NULL) {
                gray.push(tmp->right);
                depth.push(num + 1);
            }
        }
    }
    return out;
}

非递归写法2(直接摘自其他博客):

int maxDepth(TreeNode *root)
{
    if(root == NULL)
        return 0;

    int res = 0;
    queue<TreeNode *> q;
    q.push(root);
    while(!q.empty())
    {
        ++ res;
        for(int i = 0, n = q.size(); i < n; ++ i)
        {
            TreeNode *p = q.front();
            q.pop();

            if(p -> left != NULL)
                q.push(p -> left);
            if(p -> right != NULL)
                q.push(p -> right);
        }
    }

    return res;
}

 

posted @ 2018-01-17 09:53  Sherry_Yang  阅读(157)  评论(0编辑  收藏  举报