美文网首页
104. Maximum Depth of Binary Tre

104. Maximum Depth of Binary Tre

作者: 殷水臣 | 来源:发表于2017-02-21 15:28 被阅读0次

    这道题基础的不能再基础了,也没什么好说的,注意看看人家的DFS、BFS写得多好看就行,自己写的效率好渣。

    我的解法

    /**
     * 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) {
            if (root != NULL){
                return max(maxDepth(root -> left),maxDepth(root -> right)) + 1;
            }
            return 0;
        }
    };
    

    别人的解法

    别人的DFS

    这个三元运算用得好

    int maxDepth(TreeNode *root)
    {
        return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
    }
    

    BFS

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

    相关文章

      网友评论

          本文标题:104. Maximum Depth of Binary Tre

          本文链接:https://www.haomeiwen.com/subject/kqduwttx.html