[LeetCode#99]Recover Binary Search Tree

本文介绍了一种在不改变二叉搜索树结构的情况下,仅使用常数空间修复因误操作导致的两个节点交换的方法。通过深入分析中序遍历的特性,本文提出了两种情况下的解决方案,并详细阐述了实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The problem:

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?

 

My analysis:

The idea behind this problem is so elegant!!!
The key idea: we can get the swapped nodes from the inroder traversal series of the binary tree. It includes following two conditions:
1. the two swapped nodes in neighbour with each other.
Inorder traversal series: 1 ,2 ,3 ,5 ,4, 6, 7

2. the two swapped nodes are not in neighbour with each other.
Inorder traversal series: 1, 5, 3, 4, 2, 6, 7

The two cases needed to be tackled differently.
In situation 1, we would detect only one violation, the swapped nodes should be 5, 4
In situation 2, we would detect two violations, the swapped nodes should be: the pre node(5) in the first violation, and the post node(2) in the second violation.

skills in implementation:
1. Since Java pass arguments by value, we should use the ArrayList to record the target nodes we have figured out during the recursion process.
2. Swap nodes by value rather than by pointer. (don not fool in thinking about recording the parent's pointer)

 

My solution:

public class Solution {
    public void recoverTree(TreeNode root) {
        
        if (root == null) //note. the declaration's return value is void 
            return;
        
        ArrayList<TreeNode> pre = new ArrayList<TreeNode> ();
        ArrayList<TreeNode> ret = new ArrayList<TreeNode> ();
        pre.add(null);
        
        helper(root, pre, ret);//inorder to track the result, we use ArrayList.
        
        if (ret.size() > 0) {
            
            int temp = ret.get(0).val;
            ret.get(0).val = ret.get(1).val;
            ret.get(1).val = temp;
        }
        
        return;
    }
    
    private void helper(TreeNode root, ArrayList<TreeNode> pre, ArrayList<TreeNode> ret) {
        
        if (root == null)
            return;
        
        helper(root.left, pre, ret);
        
        if (pre.get(0) != null && pre.get(0).val >= root.val) {
            if (ret.size() == 0) {
                ret.add(pre.get(0));
                ret.add(root);
            } else {//we have already detected a violation 
                ret.set(1, root);
            }
        }
        pre.set(0, root);
        
        helper(root.right, pre, ret);
        
        return;
    }
}

 

转载于:https://www.cnblogs.com/airwindow/p/4212332.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值