1. 程式人生 > >LeetCode 104. Maximum Depth of Binary Tree (二叉樹的最大深度)

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.

Reference Answer

思路分析

可以參考層遍歷思路,只計數層數;

Reference Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
if not root: return 0 current_layer = [root] next_layer = [] deepth = 0 while (current_layer): deepth += 1 for node in current_layer: if node.left: next_layer.append(node.left); if
node.right: next_layer.append(node.right); current_layer = next_layer[:] next_layer = [] return deepth

Python優化版本:

做進一步優化,遞迴呼叫,只考慮層數即可。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

C++ 版本:

/**
 * 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){
            return 0;
        }
        int deepth = 0;
        queue<TreeNode*> current_node;
        // vector<TreeNode*> next_node;
        current_node.push(root);
        while (!current_node.empty()){
            ++deepth;
            int pre_count = current_node.size();
            for(int i=0; i < pre_count; i++){
                TreeNode *node =  current_node.front();
                current_node.pop();
                // current_node.pop();
                if (node->left != NULL){
                    current_node.push(node->left);
                }
                if (node->right != NULL){
                    current_node.push(node->right);
                }
            }
            
        }
        return deepth;
    }
};

C++優化版本:

/**
 * 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){
            return 0;
        }
        int left_depth = maxDepth(root->left);
        int right_depth = maxDepth(root->right);
        return max(left_depth, right_depth) + 1;
    }
};

Note:

  • 這種思路典型的遞迴呼叫,明顯不用複雜地將各層節點都儲存等,時間複雜度、空間複雜度都大大降低,要切記!切記!!!

參考文獻:

[1] https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73030