题目描述
给你一棵二叉搜索树,请 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。
示例 1:
输入: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
输出: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
示例 2:
输入: root = [5,1,7]
输出: [1,null,5,null,7]
提示:
树中节点数的取值范围是 [1, 100]
0 <= Node.val <= 1000
注意:本题与主站 897 题相同: https://leetcode.cn/problems/increasing-order-search-tree/
解法
方法一
Python3 Java C++ Go TypeScript Rust C Swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution :
def increasingBST ( self , root : TreeNode ) -> TreeNode :
head , tail = None , None
stack = []
cur = root
while stack or cur :
while cur :
stack . append ( cur )
cur = cur . left
cur = stack . pop ()
if not head :
head = cur
else :
tail . right = cur
tail = cur
cur . left = None
cur = cur . right
return head
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode increasingBST ( TreeNode root ) {
TreeNode head = null , tail = null ;
Deque < TreeNode > stack = new ArrayDeque <> ();
TreeNode cur = root ;
while ( ! stack . isEmpty () || cur != null ) {
while ( cur != null ) {
stack . push ( cur );
cur = cur . left ;
}
cur = stack . pop ();
if ( head == null ) {
head = cur ;
} else {
tail . right = cur ;
}
tail = cur ;
cur . left = null ;
cur = cur . right ;
}
return head ;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public :
TreeNode * increasingBST ( TreeNode * root ) {
TreeNode * head = nullptr , * tail = nullptr ;
stack < TreeNode *> stk ;
TreeNode * cur = root ;
while ( ! stk . empty () || cur != nullptr ) {
while ( cur != nullptr ) {
stk . push ( cur );
cur = cur -> left ;
}
cur = stk . top ();
stk . pop ();
if ( head == nullptr ) {
head = cur ;
} else {
tail -> right = cur ;
}
tail = cur ;
cur -> left = nullptr ;
cur = cur -> right ;
}
return head ;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 /**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func increasingBST ( root * TreeNode ) * TreeNode {
var head , tail * TreeNode
stack := make ([] * TreeNode , 0 )
cur := root
for len ( stack ) > 0 || cur != nil {
for cur != nil {
stack = append ( stack , cur )
cur = cur . Left
}
cur = stack [ len ( stack ) - 1 ]
stack = stack [: len ( stack ) - 1 ]
if head == nil {
head = cur
} else {
tail . Right = cur
}
tail = cur
cur . Left = nil
cur = cur . Right
}
return head
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 /**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function increasingBST ( root : TreeNode | null ) : TreeNode | null {
const dummy = new TreeNode ();
let cur = dummy ;
const dfs = ( root : TreeNode | null ) => {
if ( root == null ) {
return ;
}
dfs ( root . left );
cur . right = new TreeNode ( root . val );
cur = cur . right ;
dfs ( root . right );
};
dfs ( root );
return dummy . right ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 // Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std :: cell :: RefCell ;
use std :: rc :: Rc ;
impl Solution {
fn dfs ( root : & Option < Rc < RefCell < TreeNode >>> , vals : & mut Vec < i32 > ) {
if root . is_none () {
return ;
}
let node = root . as_ref (). unwrap (). borrow ();
Self :: dfs ( & node . left , vals );
vals . push ( node . val );
Self :: dfs ( & node . right , vals );
}
pub fn increasing_bst ( root : Option < Rc < RefCell < TreeNode >>> ) -> Option < Rc < RefCell < TreeNode >>> {
let mut vals = Vec :: new ();
Self :: dfs ( & root , & mut vals );
let mut dummy = Rc :: new ( RefCell :: new ( TreeNode :: new ( 0 )));
for & val in vals . iter (). rev () {
let mut dummy = dummy . as_ref (). borrow_mut ();
dummy . right = Some ( Rc :: new ( RefCell :: new ( TreeNode {
val ,
left : None ,
right : dummy . right . take (),
})));
}
let ans = dummy . as_ref (). borrow_mut (). right . take ();
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode * dfs ( struct TreeNode * root , struct TreeNode * cur ) {
if ( ! root ) {
return cur ;
}
cur = dfs ( root -> left , cur );
cur -> right = malloc ( sizeof ( struct TreeNode ));
cur -> right -> val = root -> val ;
cur -> right -> left = NULL ;
cur -> right -> right = NULL ;
cur = cur -> right ;
return dfs ( root -> right , cur );
}
struct TreeNode * increasingBST ( struct TreeNode * root ) {
struct TreeNode * dummy = malloc ( sizeof ( struct TreeNode ));
dfs ( root , dummy );
return dummy -> right ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 /* class TreeNode {
* var val: Int
* var left: TreeNode?
* var right: TreeNode?
* init() {
* self.val = 0
* self.left = nil
* self.right = nil
* }
* init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func increasingBST ( _ root : TreeNode ?) -> TreeNode ? {
var head : TreeNode ? = nil
var tail : TreeNode ? = nil
var stack = [ TreeNode ]()
var cur = root
while ! stack . isEmpty || cur != nil {
while cur != nil {
stack . append ( cur !)
cur = cur ?. left
}
cur = stack . removeLast ()
if head == nil {
head = cur
} else {
tail ?. right = cur
}
tail = cur
cur ?. left = nil
cur = cur ?. right
}
return head
}
}
方法二
Python3 Java C++ Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution :
def increasingBST ( self , root : TreeNode ) -> TreeNode :
def dfs ( root : TreeNode ):
if root is None :
return
dfs ( root . left )
nonlocal cur
cur . right = root
root . left = None
cur = cur . right
dfs ( root . right )
cur = dummy = TreeNode ()
dfs ( root )
return dummy . right
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private TreeNode cur ;
public TreeNode increasingBST ( TreeNode root ) {
TreeNode dummy = new TreeNode ();
cur = dummy ;
dfs ( root );
return dummy . right ;
}
private void dfs ( TreeNode root ) {
if ( root == null ) {
return ;
}
dfs ( root . left );
cur . right = root ;
root . left = null ;
cur = cur . right ;
dfs ( root . right );
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public :
TreeNode * increasingBST ( TreeNode * root ) {
TreeNode * dummy = new TreeNode ();
TreeNode * cur = dummy ;
function < void ( TreeNode * ) > dfs = [ & ]( TreeNode * root ) {
if ( ! root ) {
return ;
}
dfs ( root -> left );
cur -> right = root ;
root -> left = nullptr ;
cur = cur -> right ;
dfs ( root -> right );
};
dfs ( root );
return dummy -> right ;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 /**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func increasingBST ( root * TreeNode ) * TreeNode {
dummy := & TreeNode {}
cur := dummy
var dfs func ( * TreeNode )
dfs = func ( root * TreeNode ) {
if root == nil {
return
}
dfs ( root . Left )
root . Left = nil
cur . Right = root
cur = root
dfs ( root . Right )
}
dfs ( root )
return dummy . Right
}