Increasing Order Search Tree Solutions in Go
Number 897
Difficulty Easy
Acceptance 71.0%
Link LeetCode
Other languages C++
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodeimport ("github.com/halfrost/LeetCode-Go/structures")// TreeNode definetype TreeNode = structures.TreeNode/*** Definition for a binary tree node.* type TreeNode struct {* Val int* Left *TreeNode* Right *TreeNode* }*/// 解法一 链表思想func increasingBST(root *TreeNode) *TreeNode {var head = &TreeNode{}tail := headrecBST(root, tail)return head.Right}func recBST(root, tail *TreeNode) *TreeNode {if root == nil {return tail}tail = recBST(root.Left, tail)root.Left = nil // 切断 root 与其 Left 的连接,避免形成环tail.Right, tail = root, root // 把 root 接上 tail,并保持 tail 指向尾部tail = recBST(root.Right, tail)return tail}// 解法二 模拟func increasingBST1(root *TreeNode) *TreeNode {list := []int{}inorder(root, &list)if len(list) == 0 {return root}newRoot := &TreeNode{Val: list[0], Left: nil, Right: nil}cur := newRootfor index := 1; index < len(list); index++ {tmp := &TreeNode{Val: list[index], Left: nil, Right: nil}cur.Right = tmpcur = tmp}return newRoot}func inorder(root *TreeNode, output *[]int) {if root != nil {inorder(root.Left, output)*output = append(*output, root.Val)inorder(root.Right, output)}}