[LeetCode] Recover Binary Search Tree

Source: Internet
Author: User
Tags tree serialization

[LeetCode] 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    \     5
The above binary tree is serialized "{1,2,3,#,#,4,#,#,5}".

In the middle-order traversal, a List is used to store the positions of each node. Then, the dual pointer is directed from left to right, and the other is directed from right to left to find the wrong position. Then, the values of the connected nodes are exchanged.


/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {List
 
   list = new ArrayList<>();    public void recoverTree(TreeNode root) {    mid(root);    int left = -1;    int right = -1;    for(int i=0;i
  
   list.get(i+1).val){    left = i;    break;    }    }    for(int j=list.size()-1;j>0;j--){    if(list.get(j).val
   
    

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.