104. Maximum Depth of Binary Tre

2017-02-21  本文已影响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;
}
上一篇下一篇

猜你喜欢

热点阅读