Created
September 26, 2021 04:36
-
-
Save Allan-Gong/02d4666337f9b0ab6f127e6726bf9773 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode() {} | |
* TreeNode(int val) { this.val = val; } | |
* TreeNode(int val, TreeNode left, TreeNode right) { | |
* this.val = val; | |
* this.left = left; | |
* this.right = right; | |
* } | |
* } | |
*/ | |
class Solution { | |
public int maxDepth(TreeNode root) { | |
//. 1 | |
// / \ | |
// 2 3 | |
// ROOT -> LEAF: top to bottom | |
// Post-order: LEFT, RIGHT, ROOT: bottom to top | |
// [9], [15, 7, 20], 3 | |
// base case | |
if (root == null) return 0; // null node does not contribute to the depth of the tree | |
// max depth of subTree using root.left as root | |
int left = maxDepth(root.left); | |
int right = maxDepth(root.right); | |
// visit the current node(root) | |
// consider what to do for the current node, given the result of left subTree and right subTree | |
return 1 + Math.max(left, right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment