[LeetCode] - Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O( n ) space is pretty straight forward. Could you devise a constant space solution?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

这个题目是binary tree iterative in-order traversal的一个应用实例。中序遍历那道题里面写了如何对binary tree进行iterative的中序遍历,主要思想就是用stack来模拟递归。对这道题而言,还需要维护两个指针,pre和cur。当出现pre的值大于cur的值的时候,更新first和second指针的值。这里会有两种情况:

1. 如果是相邻的两个node调换了位置,那么pre大于cur的情况只会出现一次。

2. 如果是不相邻的两个node调换了位置,pre大于cur的情况会出现两次,需要更正的node分别为第一次的pre和第二次的cur。

在遍历结束,或者遍历过程中遇到了两次异常情况之后,对first和second指针所指向的node进行交换即可。

代码如下:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void recoverTree(TreeNode root) {
        if(root==null) return;
        
        Stack<TreeNode> stack = new Stack<TreeNode>();
        boolean flag = false;
        TreeNode cur=root, pre=null, first=null, second=null;
        while(cur!=null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if(pre == null) {
                pre = cur;
            }
            else {
                if(pre.val > cur.val) {
                    if(!flag) {
                        first = pre;
                        second = cur;
                        flag = true;
                    }
                    else {
                        second = cur;
                        break;
                    }
                }
                pre = cur;
            }
            cur = cur.right;
        }
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
        return;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值