Leetcode Recover Binary Search Tree-----java

Source: Internet
Author: User

Elements of a binary search tree (BST) is 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?

Given a sort of binary tree, and then arbitrarily exchanged two nodes, it is required to restore the original two-fork tree with constant space and without changing the structure.

If the space complexity of O (n), then the direct sequence traversal is good, now with a constant number, then only need to record two times, the middle sequence traversal, the need to move the brain.

/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution {TreeNode pre;        TreeNode first;        TreeNode second;  Public voidinorder (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; } Second=Root; } Pre=Root;    } inorder (Root.right); }         Public voidrecovertree (TreeNode root) {Pre=NULL; First=NULL; Second=NULL;        Inorder (root); if(first!=NULL&& second!=NULL){                intTMP =First.val; First.val=Second.val; Second.val=tmp; }    }}

Leetcode Recover Binary Search Tree-----java

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.