Maximum binary tree depth

分治法和遍歷法

分治比較簡單,左右結果比較後取大的再 + 1 即可

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

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left, right) + 1;
    }
}

遍歷法要想一下,我們是每次都去檢查現在是不是最大

所以需要一個變數紀錄當前最大,用全域變數記著

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

   helper(root, 1);
   return depth;
}

public void helper(TreeNode root, int curDepth) {
    if (root == null) {
        return;
    }
    if (curDepth > depth) {
        depth = curDepth;
    }
    helper(root.left, curDepth + 1);
    helper(root.right, curDepth + 1);
    return;
}

results matching ""

    No results matching ""