Leetcode:Recover Binary Search Tree

来源:互联网 发布:java时区转换 编辑:程序博客网 时间:2024/06/16 16:06

url

https://leetcode.com/problems/recover-binary-search-tree/description/

题目大意:

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?

解题思路:

二叉树的中序遍历,如果正常的BST,中序遍历是有序的,所以有我们使用中序遍历,当遇到第一个前一个值大于后一个值的时候,则我们找到了第一个位置,当我们遇到最后一个前一个值大于后一个值的时候,这个较小值的节点则是第二个位置。最后将这两个位置的值互换即可。

代码

递归解法

private void inOrder(TreeNode node){        if(node == null ) return;        inOrder(node.left);        if(prev != null && prev.val >= node.val){            if(first==null){                first = prev;            }            second = node;        }        prev = node;        inOrder(node.right);    }

迭代解法

private void inOrderIterator(TreeNode node){        TreeNode cur = node;        TreeNode prev = null;        Stack<TreeNode> stack = new Stack<>();        while(cur!=null || !stack.isEmpty()){            if(cur!=null){                stack.push(cur);                cur = cur.left;            }else{                TreeNode top = stack.pop();                if(prev!=null && prev.val>=top.val){                    if(first==null) first = prev;                    second = top;                }                prev = top;                cur = top.right;            }        }    }

Leetcode 提交代码接口实现

private TreeNode prev = null;    private TreeNode first = null;    private TreeNode second = null;    public void recoverTree(TreeNode root) {        inOrderIterator(root);        int temp = first.val;        first.val = second.val;        second.val = temp;    }
原创粉丝点击