Recover Binary Search Tree

https://www.lintcode.com/problem/recover-binary-search-tree/description

/**
 * Definition of TreeNode:
 * public class TreeNode {
 * public int val;
 * public TreeNode left, right;
 * public TreeNode(int val) {
 * this.val = val;
 * this.left = this.right = null;
 * }
 * }
 */

public class Solution {
    private TreeNode pre;
    private TreeNode m1;
    private TreeNode m2;
    /**
     * @param root: the given tree
     * @return: the tree after swapping
     */
    public TreeNode bstSwappedNode(TreeNode root) {
        // write your code here
        treeWalk(root);
        if (m1 != null) {
            int val = m1.val;
            m1.val = m2.val;
            m2.val = val;
        }
        return root;
    }

    private void treeWalk(TreeNode root) {
        if (root == null) {
            return;
        }
        treeWalk(root.left);
        if (pre != null) {
            if (pre.val > root.val) {
                //出错了
                if (m1 == null) {
                    m1 = pre;
                    m2 = root;
                } else {
                    m2 = root;
                }
            }
        }
        pre = root;
        treeWalk(root.right);
    }
}

你可能感兴趣的:(Recover Binary Search Tree)