Recover Binary Search Tree @ LeetCode

Source: Internet
Author: User
Tags tree serialization

Package Level4; import Utility. treeNode;/*** Recover Binary Search Tree ** 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? Confused what "{1, #, 2, 3}" means?> Read more on how binary tree is serialized on OJ. OJ's Binary Tree Serialization: The serialization of a binary tree follows a level order traversal, where '# 'signiies a path terminator where no node exists below. here's an example: 1/\ 2 3/4 \ 5The above binary tree is serialized as "{, 3 ,#,#, 4 ,#,#, 5 }". **/public class S99 {public static void main (String [] args) {} TreeNode pre; // point to the current traversal Element First TreeNode first; // The first out-of-order element TreeNode second; // The second out-of-order element public void inorder (TreeNode root) {if (root = null) {return;} inorder (root. left); if (pre = null) {pre = root;} else {if (pre. val> root. val) {if (first = null) {first = pre; // locate the first out-of-order element} second = root; // The second out-of-order element. If else is used, only two elements cannot be used.} pre = root; // continue searching} inorder (root. right);} public void recoverTree (TreeNode root) {pre = null; // It must be initialized here. Otherwise, the OJ will report the first = null; second = null; inorder (root); if (first! = Null & second! = Null) {// only the element value needs to be exchanged, and no pointer operation is required! Int tmp = first. val; first. val = second. val; second. val = tmp ;}}}

 

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.