Maximum Depth of Binary Tree: Recursion

Jay·2022년 5월 25일
0

Grind 120

목록 보기
19/38


First Thoughts: base case of recursion when node is leaf (node.left is null and node.right is null, or node is null), pass counter through argument, while keep adding one every time one call is made. Since return cannot return two counters, only keep the maximum of the two counts, because we're only interested in the maximum depth.

My Solution:

class Solution {
    public int maxDepth(TreeNode root) {
        if (root==null) return 0;
        int counter = doWork(root, 1);
        return counter;
    }
    public int doWork(TreeNode root, int counter) {
        if (root==null) return counter;
        if (root.left==null && root.right==null) return counter;
        int leftCount = doWork(root.left, counter+1);
        int rightCount = doWork(root.right, counter+1);
        return Math.max(leftCount, rightCount);
    }
}

Catch Point:

  1. Passing accumulator variable throughout, while incrementing by one every time it goes through the function is effective

  2. Storing the values into variables are one way to pass by one return property

  3. Returning the maximum of the two keeps track of only the maximum count

0개의 댓글