【LeetCode】104. Maximum Depth of Binary Tree(DFS|BFS)

原题

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.

分析

很简单的基础题,可以使用BFS, DFS来实现。

主要可以用来练习非递归方式的编写。

我的解答

C++ 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 bfs(struct TreeNode* root) {
        int ans = 1;
        queue< pair<TreeNode*,int> > q;
        q.push({root, 1});
        while (!q.empty()) {
            TreeNode *cur = q.front().first;
            int dep = q.front().second;
            q.pop();
            if (dep > ans)  ans = dep;
            if (cur->left)  q.push({cur->left, dep+1});
            if (cur->right) q.push({cur->right, dep+1});
        }
        return ans;
    }

    int maxDepth(TreeNode* root) {
        if (root)
            return bfs(root);
        return 0;
    }
};

C++ DFS非递归版本:

class Solution {
public:


    int dfs(struct TreeNode* root) {
        int ans = 1;
        stack< pair<TreeNode*,int> > s;
        s.push({root, 1});
        while (!s.empty()) {
            TreeNode *cur = s.top().first;
            int dep = s.top().second;
            s.pop();
            if (dep > ans)  ans = dep;
            if (cur->left)  s.push({cur->left, dep+1});
            if (cur->right) s.push({cur->right, dep+1});
        }
        return ans;
    }

    int maxDepth(TreeNode* root) {
        if (root)
            return dfs(root);
        return 0;
    }
};

哈哈,有没有发现,其实DFS和BFS的代码基本是一样的,只是一个用队列,一个用栈。

网友的解答

C++ DFS递归版:

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

Python:

def maxDepth(self, root):
    return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0

等价于下面:

if root == None:
        return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1

你可能感兴趣的:(LeetCode,递归,非递归,DFS,bfs)