码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Recover Binary Search Tree

时间:2016-01-09 20:12:12      阅读:146      评论:0      收藏: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?

思路:

中序遍历

package bst;

public class RecoverBinarySearchTree {
    
    private TreeNode prev = null;
    
    private TreeNode node1 = null;
    
    private TreeNode node2 = null;
    
    public void recoverTree(TreeNode root) {
        recoverTreeInternal(root);
        swap(node1, node2);
    }
    
    private void recoverTreeInternal(TreeNode root) {
        if (root == null) return;
        recoverTreeInternal(root.left);
        if (prev != null) {
            if (prev.val >= root.val) {
                if (node1 == null) 
                    node1 = prev;
                node2 = root;
            }
        }
        
        prev = root;
        recoverTreeInternal(root.right);        
    }
    
    private void swap(TreeNode node1, TreeNode node2) {
        if (node1 != null && node2 != null) {
            int tmp = node1.val;
            node1.val = node2.val;
            node2.val = tmp;
        }
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        RecoverBinarySearchTree r = new RecoverBinarySearchTree();
        TreeNode root = new TreeNode(0);
        TreeNode right = new TreeNode(1);
        root.left = right;
        r.recoverTree(root);
    }

}

 

LeetCode - Recover Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5116963.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!