LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Question:

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. cocould you devise a constant space solution?

Ideas:

Sequential Traversal

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);    }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.