1. 程式人生 > >LeetCode之二叉樹最大深度(簡單 二叉樹)

LeetCode之二叉樹最大深度(簡單 二叉樹)

問題描述:

給定一個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

說明: 葉子節點是指沒有子節點的節點。

示例:
給定二叉樹 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

二叉樹的問題解決大概基本兩個方向,遞迴,和佇列或者棧實現非遞迴。

遞迴

public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }else{
            int leftValue = maxDepth(root.left);
            int rightValue = maxDepth(root.right);
            return Math.max(leftValue,rightValue)+1;
        }

    }

非遞迴(這個的非遞迴有點小難度,因為每次取節點要儲存樹的深度)

import javafx.util.Pair;
import java.util.LinkedList;
import java.util.Queue;
class Solution {
    public int maxDepth(TreeNode root) {
        Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
        if (root != null) {
            queue.add(new Pair(root, 1));
        }

        int depth = 0;
        while (!queue.isEmpty()) {
            Pair<TreeNode, Integer> current = queue.poll();
            root = current.getKey();
            int current_depth = current.getValue();
            if (root != null) {
                depth = current_depth;
                queue.add(new Pair(root.left, current_depth + 1));
                queue.add(new Pair(root.right, current_depth + 1));
            }
        }
        return depth;
    }
}