Leetcode 111,104. Minimum/Maximum Depth of Binary Tree

来源:互联网 发布:洛杉矶和纽约 知乎 编辑:程序博客网 时间:2024/04/29 07:06

1. 前言

邻近毕业季, 关于算法的一些东西还是需要回顾一下的, 于是, 这里开始重新刷下Leetcode,巩固一下算法基础

2. 题目描述:

111 Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

104 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.

3. 解题思路

很容易的一道题目, 一般拿到一道关于树的题目, 主要考察的还是递归的思想, 这道题目也不例外。
首先需要注意递归到叶节点为止, 如果左右子树都存在
depth_root = min(depth_left, depth_right)
如果有一只不存在, 直接另一只的深度加1就好了

update in 20160407
今天看到了 一道 求最大深度的,感觉和这里的思路非常类似, 就顺便移到这里了。

4. 大神代码

大神的代码推荐:

// 111class Solution {public:    int minDepth(TreeNode *root) {        if(!root) return 0;        if(!root->left) return 1 + minDepth(root->right);        if(!root->right) return 1 + minDepth(root->left);        return 1+min(minDepth(root->left),minDepth(root->right));    }};

// 104

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

虽然思路是一致的, 不过代码看上去比人家的复杂了许多

5.code

这是我们刚写的代码:

/** * 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 minDepth(TreeNode* root) {        if (root == nullptr)            return 0;        int res = 0;            if (root->left && root->right){            res = min(minDepth(root->left), minDepth(root->right)) + 1;        }        else if (root->left){            res = minDepth(root->left) + 1;        }        else if (root->right){            res = minDepth(root->right) + 1;        }        else{            res = 1;        }        return res;    }};

6. 新的思路

update in 2016-04-06
今天一个不小心误入了这道题目, 于是一个不小心想到一种新的解法, 使用BFS, 而且, 个人感觉使用BFS 的搜索空间相对于 DFS 应该小那么些。。。

class Solution {public:    int minDepth(TreeNode* root) {        // bfs        if (root == nullptr)            return 0;        queue<TreeNode *> myqueue;        myqueue.push(root);        int level = 1;        while (!myqueue.empty()){            int size = myqueue.size();            for (int i = 0; i != size; i++){                TreeNode * front = myqueue.front();                myqueue.pop();                if (front->left)                    myqueue.push(front->left);                if (front->right)                    myqueue.push(front->right);                if (!front->left && !front->right)                    return level;            }            level++;        }        return level;    }};
0 0
原创粉丝点击