C++實現LeetCode(104.二叉樹的最大深度)

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

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

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

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

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

到此這篇關於C++實現LeetCode(104.二叉樹的最大深度)的文章就介紹到這瞭,更多相關C++實現二叉樹的最大深度內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: