1. 程式人生 > >LeetCode演算法題104:二叉樹的最大深度解析

LeetCode演算法題104:二叉樹的最大深度解析

給定一個二叉樹,找出其最大深度。
二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定二叉樹 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

這個題的解析我講不過官方解答,它有圖—>[link]https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/
至少遞迴法是沒什麼說得了,迭代法的話上網搜了一下,二叉樹的遍歷可以用棧來進行,和遞迴一個思路,所以還是那句話,全部遍歷一般是用棧的,如果判斷條件,從根到葉中間可以直接出去,用佇列應該效率更高一些。層次遍歷一般用棧遍歷的方法。也有DFS演算法的思想,畢竟是最大深度。(我猜如果是最小深度應該可以用BFS的思想,後面有題可以驗證一下)。
DFS思想就是朝著一條路走到黑,走不通就返回去朝另一條路走到黑,這裡的程式碼是從右邊先一條路走到底,然後往左移。
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 == NULL)
            return
0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return (leftDepth>rightDepth?leftDepth:rightDepth) + 1; } };

python3原始碼:(迭代法)

# 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 """ stack = [] if root!=None: stack.append((1, root)) depth = 0 while stack!=[]: currDepth, root = stack.pop() if root!=None: depth = max(currDepth, depth) stack.append((currDepth+1, root.left)) stack.append((currDepth+1, root.right)) return depth