Maximum Depth of Binary Tree

Maximum Depth of Binary Tree


今天是一道有關二叉樹的題目,來自LeetCode,難度為Easy,Acceptance為46.3%。

題目如下


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.

解題思路及代碼見閱讀原文

回復0000查看更多題目

解題思路


該題較為簡單,不想做過多的解釋。

首先,看到二叉樹,應該立刻就想到二叉樹的三種遍歷方式,看看哪種方法可用。

那么,這里要求二叉樹的最大深度,很容易就可以想到前序遍歷和中序遍歷不適用,而后序遍歷是適用的。即對一個節(jié)點來說,應先求左右子樹的最大深度,然后取其中較大的一個,然后加1,即為該節(jié)點的最大深度。

最后我們來看代碼。

代碼如下


Java版

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int maxDepth(TreeNode root) {
        // write your code here
        if(null == root)
            return 0;
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        return Math.max(l, r) + 1;
    }
}

關注我
該公眾號會每天推送常見面試題,包括解題思路是代碼,希望對找工作的同學有所幫助

image
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容