这里只收集了中等题

LeetCode

1. 完全二叉树的节点个数

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

leetcode#222

  1. // 递归 O(logn)
  2. func countNodes(root *TreeNode) int {
  3. if root == nil {
  4. return 0
  5. }
  6. return 1 + countNodes(root.Left) + countNodes(root.Right)
  7. }

2. 先序、中序、后序遍历

leetcode#94. 二叉树的中序遍历 leetcode#144. 二叉树的前序遍历

这里只写了中序代码

中序 递归:

  1. //时间复杂度:O(n),其中 n 为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。
  2. //空间复杂度:O(n)。空间复杂度取决于递归的栈深度,而栈深度在二叉树为一条链的情况下会达到 O(n) 的级别
  3. func inorderTraversal(root *TreeNode) (res []int) {
  4. var inorder func (node *TreeNode)
  5. inorder = func (node *TreeNode) {
  6. if node == nil {
  7. return
  8. }
  9. inorder(node.Left)
  10. res = append(res, node.Val)
  11. inorder(node.Right)
  12. }
  13. inorder(root)
  14. return
  15. }

中序 栈模拟:

  1. func threeOrders( t *TreeNode ) [][]int {
  2. s := []*TreeNode{}
  3. ret := make([][]int, 3)
  4. // 先序遍历
  5. var prev *TreeNode
  6. root := t
  7. for root != nil || len(s) > 0 {
  8. for root != nil {
  9. s = append(s, root)
  10. ret[0] = append(ret[0], root.Val)
  11. root = root.Left
  12. }
  13. root = s[len(s)-1].Right
  14. s = s[:len(s)-1]
  15. }
  16. // 中序遍历
  17. root = t
  18. for root != nil || len(s) > 0 {
  19. for root != nil {
  20. s = append(s, root)
  21. root = root.Left
  22. }
  23. root = s[len(s)-1]
  24. s = s[:len(s)-1]
  25. ret[1] = append(ret[1], root.Val)
  26. root = root.Right
  27. }
  28. // 后序遍历
  29. root = t
  30. for root != nil || len(s) > 0 {
  31. for root != nil {
  32. s = append(s, root)
  33. root = root.Left
  34. }
  35. root = s[len(s)-1]
  36. s = s[:len(s)-1]
  37. if root.Right == nil || root.Right == prev {
  38. ret[2] = append(ret[2], root.Val)
  39. prev = root
  40. root = nil
  41. } else {
  42. s = append(s, root)
  43. root = root.Right
  44. }
  45. }
  46. return ret
  47. }

Mirros算法: O(n) O(1)

https://zhuanlan.zhihu.com/p/101321696

  1. //先序
  2. func preorderTraversal(root *TreeNode) (ret []int) {
  3. if root == nil {
  4. return nil
  5. }
  6. cur := root
  7. for cur != nil {
  8. mostRight := cur.Left
  9. if mostRight != nil {
  10. for mostRight.Right != nil && mostRight.Right != cur {
  11. mostRight = mostRight.Right
  12. }
  13. if mostRight.Right == nil {
  14. mostRight.Right = cur
  15. ret = append(ret, cur.Val)
  16. cur = cur.Left
  17. continue
  18. } else {
  19. mostRight.Right = nil
  20. }
  21. } else {
  22. ret = append(ret, cur.Val)
  23. }
  24. cur = cur.Right
  25. }
  26. return
  27. }
  1. //中序
  2. func inorderTraversal(root *TreeNode) (ret []int) {
  3. if root == nil {
  4. return nil
  5. }
  6. cur := root
  7. for cur != nil {
  8. mostRight := cur.Left
  9. if mostRight != nil {
  10. for mostRight.Right != nil && mostRight.Right != cur {
  11. mostRight = mostRight.Right
  12. }
  13. if mostRight.Right == nil {
  14. mostRight.Right = cur
  15. cur = cur.Left
  16. continue
  17. } else {
  18. mostRight.Right = nil
  19. }
  20. }
  21. ret = append(ret, cur.Val)
  22. cur = cur.Right
  23. }
  24. return
  25. }
  1. //后序
  2. func reverse(a []int) {
  3. for i:=0; i<len(a)/2; i++ {
  4. a[i], a[len(a)-i-1] = a[len(a)-i-1], a[i]
  5. }
  6. }
  7. func postorderTraversal(root *TreeNode) (ret []int) {
  8. addPath := func (node *TreeNode) {
  9. resize := len(ret)
  10. for ; node != nil; node = node.Right {
  11. ret = append(ret, node.Val)
  12. }
  13. reverse(ret[resize:])
  14. }
  15. cur := root
  16. for cur != nil {
  17. mostRight := cur.Left
  18. if mostRight != nil {
  19. for mostRight.Right != nil && mostRight.Right != cur {
  20. mostRight = mostRight.Right
  21. }
  22. if mostRight.Right == nil {
  23. mostRight.Right = cur
  24. cur = cur.Left
  25. continue
  26. } else {
  27. mostRight.Right = nil
  28. addPath(cur.Left)
  29. }
  30. }
  31. cur = cur.Right
  32. }
  33. addPath(root)
  34. return
  35. }

105. 从前序与中序遍历序列构造二叉树

时间复杂度:O(n),其中 n 是树中的节点个数。

空间复杂度:O(n),除去返回的答案需要的 O(n) 空间之外,我们还需要使用 O(n) 的空间存储哈希映射,以及 O(h)(其中 h 是树的高度)的空间表示递归时栈空间。这里 h < n,所以总空间复杂度为O(n)。

  1. // 递归构建
  2. func buildTree(preorder []int, inorder []int) *TreeNode {
  3. if len(preorder)<=0 || len(inorder) <= 0 {
  4. return nil
  5. }
  6. root := &TreeNode{}
  7. root.Val = preorder[0]
  8. idx := 0
  9. for ; idx<len(inorder); idx++ {
  10. if inorder[idx] == root.Val {
  11. break
  12. }
  13. }
  14. root.Left = buildTree(preorder[1:idx+1], inorder[:idx])
  15. root.Right = buildTree(preorder[idx+1:], inorder[idx+1:])
  16. return root
  17. }

还有迭代方式:有点复杂,有空研究补充

106. 从中序与后序遍历序列构造二叉树

时间复杂度:O(n),其中 n 是树中的节点个数。

空间复杂度:O(n),除去返回的答案需要的 O(n) 空间之外,我们还需要使用 O(n) 的空间存储哈希映射,以及 O(h)(其中 h 是树的高度)的空间表示递归时栈空间。这里 h < n,所以总空间复杂度为O(n)。

  1. // 递归方式
  2. func buildTree(inorder []int, postorder []int) *TreeNode {
  3. if len(postorder) == 0 {
  4. return nil
  5. }
  6. root := &TreeNode{postorder[len(postorder)-1], nil, nil}
  7. i := 0
  8. for ; i < len(inorder); i++ {
  9. if inorder[i] == postorder[len(postorder)-1] {
  10. break
  11. }
  12. }
  13. // 中序数组按后序最后一个数左右切分;后序数组按中序左右切片的长度划分,却掉最后一个
  14. root.Left = buildTree(inorder[:i], postorder[:i])
  15. root.Right = buildTree(inorder[i+1:], postorder[i:len(postorder)-1])
  16. return root
  17. }

还有迭代方式:有点复杂,有空研究补充

110. 平衡二叉树

解法1:自定向下递归 。先判断当前节点是否平衡,在判断左右子树是否平衡

时间复杂度:O(n ^ 2),其中 n 是二叉树中的节点个数。
最坏情况下,二叉树是满二叉树,需要遍历二叉树中的所有节点,时间复杂度是O(n)。
对于节点 p,如果它的高度是 d,则 height(p) 最多会被调用 d 次(即遍历到它的每一个祖先节点时)。对于平均的情况,一棵树的高度 h 满足O(h)=O(logn),因为 d≤h,所以总时间复杂度为O(nlogn)。对于最坏的情况,二叉树形成链式结构,高度为 O(n),此时总时间复杂度为 O(n^2)

空间复杂度:O(n),其中 n 是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数最大不会超过 n

  1. func isBalanced(root *TreeNode) bool {
  2. if root == nil {
  3. return true
  4. }
  5. return abs(height(root.Left) - height(root.Right)) <= 1 && isBalanced(root.Left) && isBalanced(root.Right)
  6. }
  7. func height(root *TreeNode) int {
  8. if root == nil {
  9. return 0
  10. }
  11. return max(height(root.Left), height(root.Right)) + 1
  12. }
  13. func max(a, b int) int {
  14. if a > b {
  15. return a
  16. }
  17. return b
  18. }
  19. func abs(a int) int {
  20. if a < 0 {
  21. return -1 * a
  22. }
  23. return a
  24. }

可以拿到offer的解法:

自底向上的递归:先判断左右子树是否平衡,再判断当前节点是否平衡

自底向上递归的做法类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。如果一棵子树是平衡的,则返回其高度(高度一定是非负整数),否则返回 -1−1。如果存在一棵子树不平衡,则整个二叉树一定不平衡。

  1. func isBalanced(root *TreeNode) bool {
  2. if root == nil {
  3. return true
  4. }
  5. return height(root) >= 0
  6. }
  7. func height(root *TreeNode) int {
  8. if root == nil {
  9. return 0
  10. }
  11. leftHeight := height(root.Left)
  12. rightHeight := height(root.Right)
  13. if abs(leftHeight - rightHeight) > 1 || leftHeight == -1 || rightHeight == -1 {
  14. return -1
  15. }
  16. return max(leftHeight, rightHeight) + 1
  17. }
  18. func max(a, b int) int {
  19. if a > b {
  20. return a
  21. }
  22. return b
  23. }
  24. func abs(a int) int {
  25. if a < 0 {
  26. return -1 * a
  27. }
  28. return a
  29. }

5. 层序遍历

题目描述:给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

示例:

输入:[1,2,3,4,5,null,7,8]

  1. 1
  2. / \
  3. 2 3
  4. / \ \
  5. 4 5 7
  6. /
  7. 8

输出:[[1],[2,3],[4,5,7],[8]]

leetcode#面试题 04.03. 特定深度节点链表

  1. func listOfDepth(tree *TreeNode) []*ListNode {
  2. q := []*TreeNode{tree} // 层序队列
  3. ret := make([]*ListNode, 0)
  4. for len(q) > 0 {
  5. lhead := &ListNode{}
  6. cur := lhead
  7. p := []*TreeNode{} // 层序队列更新
  8. for j := 0; j < len(q); j++ {
  9. node := &ListNode{Val: q[j].Val, Next: nil}
  10. cur.Next = node
  11. cur = node
  12. if q[j].Left != nil {
  13. p = append(p, q[j].Left)
  14. }
  15. if q[j].Right != nil {
  16. p = append(p, q[j].Right)
  17. }
  18. }
  19. ret = append(ret, lhead.Next)
  20. q = p
  21. }
  22. return ret
  23. }

6. 叶子统计

7. 最大二叉树 I

题目描述:给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

  • 二叉树的根是数组中的最大元素。
  • 左子树是通过数组中最大值左边部分构造出的最大二叉树。
  • 右子树是通过数组中最大值右边部分构造出的最大二叉树。
  • 通过给定的数组构建最大二叉树,并且输出这个树的根节点。

输入:[3,2,1,6,0,5]
输出:返回下面这棵树的根节点:

  1. 6
  2. / \
  3. 3 5
  4. \ /
  5. 2 0
  6. \
  7. 1

解法一:递归

时间O(n^2) 一共被调用 n 次。每次递归寻找根节点时,需要遍历当前索引范围内所有元素找出最大值。一般情况下,每次遍历的复杂度为 O(logn),总复杂度为 O(nlogn)。最坏的情况下,数组 nums 有序,总的复杂度为 O(n^2)。

空间 O(n)

  1. func constructMaximumBinaryTree(nums []int) *TreeNode {
  2. if len(nums) == 0 {
  3. return nil
  4. }
  5. max, idx := nums[0], 0
  6. for i := 0; i < len(nums); i++ {
  7. if nums[i] > max {
  8. max = nums[i]
  9. idx = i
  10. }
  11. }
  12. node := &TreeNode{Val: max, Left: nil, Right: nil}
  13. node.Left = constructMaximumBinaryTree(nums[0:idx])
  14. node.Right = constructMaximumBinaryTree(nums[idx+1:])
  15. return node
  16. }

解法二:

  • 依次插入,先选取首项为root。
  • 接下来每一项:如果小于root,则插入root的右树(insertRight);如果大于root,则选取该点为新root,将原树变为新root的左树(reRoot)
  • 实现insertRight与reRoot函数

时间O(n) 最坏n^2

  1. func constructMaximumBinaryTree(nums []int) *TreeNode {
  2. if len(nums) == 0 {
  3. return nil
  4. }
  5. root := &TreeNode{Val: nums[0]}
  6. for _, num := range nums[1:] {
  7. root = insert(num, root)
  8. }
  9. return root
  10. }
  11. func insert(val int, root *TreeNode) *TreeNode {
  12. if val < root.Val {
  13. insertRight(val, root) // 插入右树
  14. return root
  15. }
  16. return reRoot(val, root)
  17. }
  18. // 插入root的右树
  19. // 对于右树路径上的节点,如果遇到小于该值的节点。将该值作为新节点,原节点作为新节点的左树
  20. func insertRight(val int, root *TreeNode) {
  21. cur := root
  22. for {
  23. if cur.Right != nil {
  24. if cur.Right.Val < val {
  25. cur.Right = reRoot(val, cur.Right)
  26. return
  27. }
  28. cur = cur.Right
  29. } else {
  30. cur.Right = &TreeNode{Val: val}
  31. return
  32. }
  33. }
  34. }
  35. // 修改根为新节点并将原树赋给新root的左节点
  36. func reRoot(val int, root *TreeNode) (node *TreeNode) {
  37. node = &TreeNode{Val: val, Left: nil, Right: nil}
  38. node.Left = root
  39. return
  40. }

998. 最大二叉树 II

问题:向一颗最大二叉树中插入一个节点。

解题思路:复用上面 7. 最大二叉树 I 中的第二种解法,插入节点

998. 最大二叉树 II

代码略

589. N叉树的前序遍历

递归:

  1. func preorder(root *Node) []int {
  2. if root == nil {
  3. return nil
  4. }
  5. ret := make([]int, 0)
  6. var f func (root *Node)
  7. f = func (root *Node) {
  8. ret = append(ret, root.Val)
  9. if root.Children == nil {
  10. return
  11. }
  12. for _, child := range root.Children {
  13. f(child)
  14. }
  15. }
  16. f(root)
  17. return ret
  18. }

迭代(用栈):

  1. func preorder(root *Node) []int {
  2. if root == nil {
  3. return nil
  4. }
  5. var ret []int
  6. var stack []*Node
  7. stack = append(stack, root)
  8. for len(stack) > 0 {
  9. node := stack[len(stack)-1]
  10. stack = stack[:len(stack)-1]
  11. ret = append(ret, node.Val)
  12. for i := len(node.Children)-1; i >= 0; i-- {
  13. stack = append(stack, node.Children[i])
  14. }
  15. }
  16. return ret
  17. }

111. 二叉树的最小深度

递归

  1. func minDepth(root *TreeNode) int {
  2. if root == nil {
  3. return 0
  4. }
  5. if root.Left == nil {
  6. return minDepth(root.Right)+1
  7. }
  8. if root.Right == nil {
  9. return minDepth(root.Left)+1
  10. }
  11. return min(minDepth(root.Left), minDepth(root.Right))+1
  12. }
  13. func min(a, b int) int {
  14. if a < b {
  15. return a
  16. }
  17. return b
  18. }

Mirrors算法:

  1. func minDepth(root *TreeNode) int {
  2. if root == nil {
  3. return 0
  4. }
  5. minD := math.MaxInt32
  6. cur := root
  7. curL := 0
  8. for cur != nil {
  9. mostRight := cur.Left
  10. if mostRight != nil {
  11. mostRightHeight := 1
  12. for mostRight.Right != nil && mostRight.Right != cur {
  13. mostRight = mostRight.Right
  14. mostRightHeight++
  15. }
  16. if mostRight.Right == nil {
  17. mostRight.Right = cur
  18. cur = cur.Left
  19. curL++
  20. continue
  21. } else {
  22. mostRight.Right = nil
  23. if mostRight.Left == nil && minD > curL {
  24. minD = curL
  25. }
  26. curL -= mostRightHeight
  27. }
  28. } else {
  29. curL++
  30. }
  31. cur = cur.Right
  32. }
  33. RightHeight := 1
  34. for root.Right != nil {
  35. RightHeight++
  36. root = root.Right
  37. }
  38. if root.Left == nil && RightHeight < minD {
  39. minD = RightHeight
  40. }
  41. return minD
  42. }

104. 二叉树的最大深度(递归和bfs)

bfs 空间O(1)

  1. func maxDepth(root *TreeNode) (ans int) {
  2. if root == nil {
  3. return 0
  4. }
  5. s := []*TreeNode{}
  6. s = append(s, root)
  7. for len(s) > 0 {
  8. siz := len(s)
  9. for siz > 0 {
  10. n := s[0]
  11. s = s[1:]
  12. if n.Left != nil {
  13. s = append(s, n.Left)
  14. }
  15. if n.Right != nil {
  16. s = append(s, n.Right)
  17. }
  18. siz--
  19. }
  20. ans++
  21. }
  22. return ans
  23. }

124. 二叉树中的最大路径和

  1. // 在树上, 设 dp[C] 代表以当前节点为结尾的最大上升路径和,
  2. // 则我们需要对节点的左右子树做一个选择, 有
  3. // dp[C] = max(max(dp[L], 0), max(dp[R], 0)) + C.val
  4. // 式中, C,L,R 分别代指 当前节点、左子节点、右子节点。
  5. func maxPathSum(t *TreeNode) int {
  6. ans := math.MinInt32
  7. var dfs func (*TreeNode) int
  8. dfs = func (root *TreeNode) int {
  9. if root == nil {
  10. return 0
  11. }
  12. left := max(dfs(root.Left), 0)
  13. right := max(dfs(root.Right), 0)
  14. val := left + right + root.Val
  15. ans = max(ans, val)
  16. return max(left, right) + root.Val
  17. }
  18. dfs(t)
  19. return ans
  20. }
  21. func max(a, b int) int {
  22. if a > b {
  23. return a
  24. }
  25. return b
  26. }

剑指Offer

剑指 Offer 26. 树的子结构

  1. //递归判断 O(mn)
  2. func isSubStructure(A *TreeNode, B *TreeNode) bool {
  3. return (A != nil && B != nil) && (recur(A, B) || isSubStructure(A.Left, B) || isSubStructure(A.Right, B))
  4. }
  5. //递归判断当前节点开始的每一个节点是否相同,不同则false
  6. func recur(A *TreeNode, B *TreeNode) bool {
  7. if B == nil {
  8. return true
  9. }
  10. if A == nil || A.Val != B.Val {
  11. return false
  12. }
  13. return recur(A.Left, B.Left) && recur(A.Right, B.Right)
  14. }

剑指 Offer 37. 序列化二叉树

  1. class Codec:
  2. def serialize(self, root):
  3. if not root:
  4. return "[]"
  5. queue = collections.deque()
  6. queue.append(root)
  7. res = []
  8. while queue:
  9. node = queue.popleft()
  10. if node:
  11. res.append(str(node.val))
  12. queue.append(node.left)
  13. queue.append(node.right)
  14. else:
  15. res.append("null")
  16. return "[" + ','.join(res) + ']'
  17. def deserialize(self, data):
  18. if data == "[]":
  19. return None
  20. vals, i = data[1:-1].split(","), 1
  21. root = TreeNode(int(vals[0]))
  22. queue = collections.deque()
  23. queue.append(root)
  24. while queue:
  25. node = queue.popleft()
  26. if vals[i] != "null":
  27. node.left = TreeNode(int(vals[i]))
  28. queue.append(node.left)
  29. i += 1
  30. if vals[i] != "null":
  31. node.right = TreeNode(int(vals[i]))
  32. queue.append(node.right)
  33. i += 1
  34. return root
  1. public class Codec {
  2. public String serialize(TreeNode root) {
  3. if (root == null) {
  4. return "[]";
  5. }
  6. Queue<TreeNode> q = new LinkedList<>();
  7. q.add(root);
  8. StringBuilder sb = new StringBuilder();
  9. sb.append("[");
  10. while (!q.isEmpty()) {
  11. TreeNode node = q.poll();
  12. if (node != null) {
  13. sb.append(node.val + ",");
  14. q.add(node.left);
  15. q.add(node.right);
  16. } else {
  17. sb.append("null,");
  18. }
  19. }
  20. sb.deleteCharAt(sb.length() - 1);
  21. sb.append("]");
  22. return sb.toString();
  23. }
  24. public TreeNode deserialize(String data) {
  25. if (data == "[]") {
  26. return null;
  27. }
  28. String[] vals = data.substring(1, data.length() - 1).split(",");
  29. TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
  30. Queue<TreeNode> q = new LinkedList<>();
  31. q.add(root);
  32. int index = 1;
  33. while (!q.isEmpty()) {
  34. TreeNode node = q.poll();
  35. if (!vals[index].equals("null")) {
  36. node.left = new TreeNode(Integer.parseInt(vals[index]));
  37. q.add(node.left);
  38. }
  39. index++;
  40. if (!vals[index].equals("null")) {
  41. node.right = new TreeNode(Integer.parseInt(vals[index]));
  42. q.add(node.right);
  43. }
  44. index++;
  45. }
  46. return root;
  47. }
  48. }

剑指 Offer 68 - I. 二叉搜索树的最近公共祖先

  1. class Solution {
  2. public:
  3. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  4. if (root == NULL || root == p || root == q) {
  5. return root;
  6. }
  7. if (p->val < root->val && q->val < root->val) {
  8. return lowestCommonAncestor(root->left, p, q);
  9. } else if (p->val > root->val && q->val > root->val) {
  10. return lowestCommonAncestor(root->right, p, q);
  11. }
  12. return root;
  13. }
  14. };
  15. // 同理最远公共祖先
  16. // 未测试,估计正确
  17. class Solution {
  18. public:
  19. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  20. if (root == NULL || root == p || root == q) {
  21. return root;
  22. }
  23. if (p->val < root->val && q->val > root->val) {
  24. return root;
  25. } else if (p->val < root->val && q->val < root->val) {
  26. return lowestCommonAncestor(root->left, p, q);
  27. } else if (p->val > root->val && q->val > root->val) {
  28. return lowestCommonAncestor(root->right, p, q);
  29. }
  30. return NULL;
  31. }
  32. };

剑指 Offer 68 - II. 二叉树的最近公共祖先

思路:dfs

  1. class Solution {
  2. public:
  3. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  4. if (root == NULL || root == p || root == q) return root;
  5. TreeNode* left = lowestCommonAncestor(root->left, p, q);
  6. TreeNode* right = lowestCommonAncestor(root->right, p, q);
  7. if (left == NULL) return right;
  8. if (right == NULL) return left;
  9. return root; // p, q 分布在root的两边
  10. }
  11. };

【未找到】多叉树的最近公共祖先

思路: 转化成两个链表的交点问题解决