Recover Binary Search Tree

62 篇文章 0 订阅

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?

思路:inorder travel; 注意第一次 pre > cur, 的时候,要记录两个值,然后第二次pre > cur的时候就cur值就好了;

注意传参数是传array,或者用全局变量;

/**
 * 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 void recoverTree(TreeNode root) {
        TreeNode[] res = new TreeNode[] {null, null};
        InOrderTraverse(root, res);
    }
    
    private void InOrderTraverse(TreeNode root, TreeNode[] res) {
        Stack<TreeNode> stack = new Stack<>();
        pushLeft(root, stack);
        
        TreeNode pre = null;
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if(pre == null) {
                pre = node;
            } else {
                if(pre.val > node.val) {
                    if(res[0] == null) {
                        res[0] = pre;
                        res[1] = node;
                    } else {
                        res[1] = node;
                        break;
                    }
                }
                pre = node;
            }
            if(node.right != null) {
                pushLeft(node.right, stack);
            }
        }
        
        // swap res[0] & res[1];
        int temp = res[0].val;
        res[0].val = res[1].val;
        res[1].val = temp;
    }
    
    private void pushLeft(TreeNode node, Stack<TreeNode> stack) {
        while(node != null) {
            stack.push(node);
            node = node.left;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值