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.

題意:求一個二叉樹的最大深度。

思路:
這道題用分治的思路非常容易解決,在根節點不是null的情況下,一棵樹的最大高度等于左右子樹的最大高度加1.
用深度搜索的方法,也可以找出一條最長的路徑,即最大高度。
用寬度搜索的方法,也能找出最深一層,得到最大高度。

下面是分治解法的代碼:

public int maxDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }

    int left = maxDepth(root.left);
    int right = maxDepth(root.right);

    return 1 + Math.max(left, right);
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容