File tree Expand file tree Collapse file tree
maximum-depth-of-binary-tree Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * public class TreeNode {
4+ * int val;
5+ * TreeNode left;
6+ * TreeNode right;
7+ * TreeNode() {}
8+ * TreeNode(int val) { this.val = val; }
9+ * TreeNode(int val, TreeNode left, TreeNode right) {
10+ * this.val = val;
11+ * this.left = left;
12+ * this.right = right;
13+ * }
14+ * }
15+ */
16+
17+ // Good solution from Leetcode
18+ // class Solution{
19+ // public int maxDepth(TreeNode root){
20+ // if (root==null) return 0;
21+ // return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
22+ // }
23+ // }
24+
25+ class Solution {
26+ // TC : O(n)
27+ // SC : O(h) height of tree(DFS), width of tree(BFS)
28+ public int maxDepth (TreeNode root ) {
29+ return dfs (root , 0 );
30+ }
31+
32+ private int dfs (TreeNode cursor , int depth ) {
33+ if (cursor == null ) {
34+ return depth ;
35+ }
36+ return Math .max (
37+ dfs (cursor .left , depth + 1 ),
38+ dfs (cursor .right , depth + 1 ));
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments