website/content/ChapterFour/0800~0899/0897.Increasing-Order-Search-Tree.md
Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1:
Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
1
\
2
\
3
\
4
\
5
\
6
\
7
\
8
\
9
Note:
给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
提示:
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一 链表思想
func increasingBST(root *TreeNode) *TreeNode {
var head = &TreeNode{}
tail := head
recBST(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 := newRoot
for index := 1; index < len(list); index++ {
tmp := &TreeNode{Val: list[index], Left: nil, Right: nil}
cur.Right = tmp
cur = 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)
}
}