File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """
2+ The tree is balanced if
3+ 1. Left child and right child are balanced
4+ 2. |left_max_depth - right_max_depth| must smaller or equal to 1
5+
6+ So the helper() will check condition 1. and 2. by `if l!=-1 and r!=-1 and abs(l-r)<=1`
7+ if true, the node is balanced, return the depth
8+ if not, the node is not balanced, return -1
9+ """
10+ class Solution (object ):
11+ def isBalanced (self , root ):
12+
13+ def helper (node , depth ):
14+ if not node .left and not node .right : return depth
15+
16+ l = r = depth #l: left_max_depth, r: right_max_depth
17+ if node .left :
18+ l = helper (node .left , depth + 1 )
19+ if node .right :
20+ r = helper (node .right , depth + 1 )
21+
22+ if l != - 1 and r != - 1 and abs (l - r )<= 1 :
23+ return max (l , r )
24+ return - 1
25+
26+ if not root : return True
27+ return helper (root , 0 )!= - 1
Original file line number Diff line number Diff line change 1+ """
2+ Time complexity: O(N), N is the number of nodes. Becasue we use DFS to traverse all the nodes.
3+ Space complexity: O(N), N is the number of nodes. Becasue the stack may potentially store all the nodes.
4+ """
5+ class Solution (object ):
6+ def maxDepth (self , root ):
7+ if not root : return 0
8+
9+ stack = []
10+ stack .append ((root , 1 ))
11+ max_depth = 0
12+
13+ while stack :
14+ node , depth = stack .pop ()
15+ max_depth = max (max_depth , depth )
16+ if node .left :
17+ stack .append ((node .left , depth + 1 ))
18+ if node .right :
19+ stack .append ((node .right , depth + 1 ))
20+ return max_depth
21+
You can’t perform that action at this time.
0 commit comments