balanced binary tree

Enter the root node of a binary tree to determine whether the tree is a balanced binary tree. If the depth difference between the left and right subtrees of any node in a binary tree does not exceed 1, it is a balanced binary tree. If it is balance two

Depth of binary tree

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func maxDepth(root *TreeNode) int { if root == nil { return 0 } var max func(a, b int) int max = func(a, b int) int { if a > b { return a } return b } return max(maxDepth(root.Left), maxDepth(root.Right))

Postorder traversal of binary tree

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func postorderTraversal(root *TreeNode) []int { var res []int var poster func(root *TreeNode) poster = func(root *TreeNode) { if root == nil { return } poster(root.Left) poster(root.Right) res = append(res, root.Val) } poster(root) return res }

Preorder traversal of binary tree

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func preorderTraversal(root *TreeNode) []int { var res []int var preorder func(root *TreeNode) preorder = func(root *TreeNode) { if root == nil { return } res = append(res, root.Val) preorder(root.Left) preorder(root.Right) } preorder(root) return res }

Square root of

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 func mySqrt(x int) int { l, r := 0, x ans := -1 for l <= r { mid := l + (r-l)/2 if mid*mid == x { return mid } else if mid*mid < x { ans = mid l = mid + 1 } else { r = mid - 1 }