[Leetcode] 99. Recover Binary Search Tree Java

Source: Internet
Author: User

Topic:

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?

test instructions and analysis: two point order of a binary search tree is wrong, restore it. to find two points of the sequential exchange, the exchange point is a couple of situations: (1) One is the adjacent two points exchange, so that only one reverse order (2) is not adjacent two points exchange, there are two reverse, the two points of the exchange is the first reverse of the first point and second order of the second point, find these two points, and then swap.

Code:

/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/classSolution {TreeNode Firstnode=NULL; TreeNode Secondnode=NULL; TreeNode prevelement=NewTreeNode (Integer.min_value);  Public voidRecovertree (TreeNode root) {//two point order of a binary search tree is wrong, restore it//to find two points of the sequential exchange, the exchange point is a couple of situations: (1) One is the adjacent two points exchange, so that only one reverse order (2) is not adjacent two points exchange, there are two reverse, the two points of the exchange is the first reverse of the first point and second order of the second point, find these two points, Then swaptraverse (root); inttemp =Firstnode.val; Firstnode.val=Secondnode.val; Secondnode.val=temp; }     Public voidTraverse (TreeNode node) {if(node = =NULL)            return;        Traverse (Node.left); if(Firstnode = =NULL&& prevelement.val >= node.val) {//ReverseFirstnode =prevelement; }        if(firstnode!=NULL&& prevelement.val>=node.val) Secondnode=node; Prevelement=node;    Traverse (node.right); }}

[Leetcode] 99. Recover Binary Search Tree Java

Related Article

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.