Skip to content

Commit fb7fa58

Browse files
sangam14saiyam1814
authored andcommitted
Create balanced_bianry_tree.go
1 parent f1cee26 commit fb7fa58

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package balanced_bianry_tree
2+
3+
type TreeNode struct {
4+
Val int
5+
Left *TreeNode
6+
Right *TreeNode
7+
}
8+
9+
func isBalanced(root *TreeNode) bool {
10+
_, ret := helper(root)
11+
return ret
12+
}
13+
14+
func helper(root *TreeNode) (int, bool) {
15+
if root == nil {
16+
return 0, true
17+
}
18+
leftDepth, leftRet := helper(root.Left)
19+
if !leftRet {
20+
return -1, false
21+
}
22+
rightDepth, rightRet := helper(root.Right)
23+
if !rightRet {
24+
return -1, false
25+
}
26+
if leftDepth > 1+rightDepth || rightDepth > 1+leftDepth {
27+
return -1, false
28+
}
29+
depth := 1 + leftDepth
30+
if rightDepth > leftDepth {
31+
depth = 1 + rightDepth
32+
}
33+
return depth, true
34+
}

0 commit comments

Comments
 (0)