Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Created September 26, 2021 04:36
Show Gist options
  • Save Allan-Gong/02d4666337f9b0ab6f127e6726bf9773 to your computer and use it in GitHub Desktop.
Save Allan-Gong/02d4666337f9b0ab6f127e6726bf9773 to your computer and use it in GitHub Desktop.
/**
* 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