欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++實(shí)現(xiàn)LeetCode(104.二叉樹的最大深度)

 更新時間:2021年07月21日 15:34:03   作者:Grandyang  
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(104.二叉樹的最大深度),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

[LeetCode] 104. Maximum Depth of Binary Tree 二叉樹的最大深度

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9  20
/  \
15   7

return its depth = 3.

求二叉樹的最大深度問題用到深度優(yōu)先搜索 Depth First Search,遞歸的完美應(yīng)用,跟求二叉樹的最小深度問題原理相同,參見代碼如下:

C++ 解法一:

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

Java 解法一:

public class Solution {
    public int maxDepth(TreeNode root) {
        return root == null ? 0 : (1 + Math.max(maxDepth(root.left), maxDepth(root.right)));
    }
}

我們也可以使用層序遍歷二叉樹,然后計數(shù)總層數(shù),即為二叉樹的最大深度,注意 while 循環(huán)中的 for 循環(huán)的寫法有個 trick,一定要將 q.size() 放在初始化里,而不能放在判斷停止的條件中,因?yàn)閝的大小是隨時變化的,所以放停止條件中會出錯,參見代碼如下:

C++ 解法二:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            ++res;
            for (int i = q.size(); i > 0; --i) {
                TreeNode *t = q.front(); q.pop();
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
        }
        return res;
    }
};

Java 解法二:

public class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        int res = 0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            ++res;
            for (int i = q.size(); i > 0; --i) {
                TreeNode t = q.poll();
                if (t.left != null) q.offer(t.left);
                if (t.right != null) q.offer(t.right);
            }
        }
        return res;
    }
}

Github 同步地址:

https://github.com/grandyang/leetcode/issues/104

類似題目:

Balanced Binary Tree

Minimum Depth of Binary Tree

Maximum Depth of N-ary Tree

參考資料:

https://leetcode.com/problems/maximum-depth-of-binary-tree/

https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/34207/my-code-of-c-depth-first-search-and-breadth-first-search

到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(104.二叉樹的最大深度)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)二叉樹的最大深度內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論