leetcode-99. Recover Binary Search Tree

The bst(binary search tree)'s inorder traverse is ascend. In the following solution, I created an assistant point to record current subtree’s root’s pre nodes in inorder traverse. The key point here is that exactly two nodes were swapped. which could result in one or two inverse pairs. Suppose the sequence is a1,a2, …, an and ai, aj which is in the sequence is the inverse pair nodes, and if ai is next to aj, only one inverse pair <ai, aj> will be found, and when ai isn’t next to aj, two inverse pairs would be found, which is <ai, ai+1> and <aj-1, aj> (i < j). So in the swap function, when I find the first inverse pair, I just save it and when I found a second inverse pair, I exchange ai and aj which is a[0] and root to recover the tree. And if I don’t find a second inverse pair, I can now make a conclusion that ai is next to aj, so I just need to exchange a[0] and a[1] which is exactly ai and aj. And the time complexity is the same as space complexity which is O(n).

func swap(pre **TreeNode, root *TreeNode, a []*TreeNode, exchanged *bool){
    if (*pre)!=nil{
        if (*pre).Val < root.Val{
            //normal
        }else{
            if a[0]==nil {
                a[0]=*pre
                a[1]=root
            }else{
                temp:=root.Val
				root.Val=a[0].Val
				a[0].Val=temp
                (*exchanged)=true
            }
        }
    }
}

func fakeRecoverTree(pre **TreeNode, root *TreeNode, a []*TreeNode, exchanged *bool)  {
	if root==nil{
        return
    }
    fakeRecoverTree(pre,root.Left,a,exchanged)
    swap(pre,root,a,exchanged)
    *pre=root
    fakeRecoverTree(pre,root.Right,a,exchanged)
}

func recoverTree(root *TreeNode)  {
    var a []*TreeNode = []*TreeNode{nil,nil}
    var pre *TreeNode = nil
    var exchanged bool=false
	fakeRecoverTree(&pre,root,a,&exchanged)
    if !exchanged&&a[1]!=nil{
        temp:=a[1].Val
		a[1].Val=a[0].Val
		a[0].Val=temp
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值