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?

思路:题目要求使用常量空间回复二叉树,如果没有这个要求,递归的中序遍历就可以(递归的时候需要栈,空间不是常亮的)。但是Leetcode里的高票答案采用的这一方法,我表示不是很理解。

所以我采用的方法是morris遍历(线索二叉树)+记录中序下位置不符合搜索树的两个节点,记录下值即可。关于不符合位置的点,其可能最多为两对,最少为一对,所以取其中最大者与最小者即为需要交换的点。(可能这里复杂了,需要优化)。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
	public void morris(TreeNode n) {
		TreeNode[] res = new TreeNode[2];// _0 : min,_1:max
		TreeNode front = null, back = null;
		TreeNode cur = n;
		TreeNode pre = null;
		
		while (cur != null) {
			if (cur.left == null) {
				// print(cur);
				System.out.println(cur.val);
				front = back;
				back = cur;
				//System.out.println("front,back "+front+" , "+back);
				if (front != null && back != null) {
					if (front.val >= back.val) {
						res[0] = (res[0] == null) ? back : ((back.val < res[0].val) ? back : res[0]);
						res[1] = (res[1] == null) ? front : ((front.val > res[1].val) ? front : res[1]);
					}				
				}			
				cur = cur.right;
			} else {
				pre = cur.left;
				while (pre.right != null && pre.right != cur)
					pre = pre.right;
				if (pre.right == null) {
					pre.right = cur;
					cur = cur.left;
				} else {
					// print(cur)
					front = back;
					back = cur;
					//System.out.println("front,back "+front.val+" , "+back.val);
					if (front != null && back != null) {
						if (front.val >= back.val) {
							res[0] = (res[0] == null) ? back : ((back.val < res[0].val) ? back : res[0]);
							res[1] = (res[1] == null) ? front : ((front.val > res[1].val) ? front : res[1]);
						}						
					}				
					pre.right = null;
					System.out.println(cur.val);
					cur = cur.right;
				}				
			}
		}
		int temp = res[0].val;
		res[0].val = res[1].val;
		res[1].val = temp;
	}

	public void recoverTree(TreeNode root) {
		morris(root);
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值