[Leetcode] Recover Binary Search Tree

Source: Internet
Author: User
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?

 

Algorithm ideas:

Train of Thought 1: Find the Middle-order traversal sequence, space complexity O (N), tip requires that only the O (1) space can be opened.

Code omitted

Train of Thought 2: In the middle order traversal, every vertex is recorded as its precursor, record the previous node pre of the current pointer cur, if pre. val is greater than cur. val indicates the wrong order. In most cases, there are two wrong orders. If there is one wrong order, it means that adjacent nodes need to be exchanged.

 1 public class Solution { 2     TreeNode first = null,second = null,pre = null; 3     public void recoverTree(TreeNode root) { 4         findNode(root); 5         swap(first, second); 6     } 7     private void findNode(TreeNode root){ 8         if(root == null){ 9             return;10         }11         if(root.left != null )  findNode(root.left);12         if(pre != null && root.val < pre.val){13             if(first == null){14                 first = pre;15             }16             second = root;17         }18         pre = root;19         if(root.right != null)  findNode(root.right);20     }21     private void swap(TreeNode node1,TreeNode node2){22         int tem = node1.val;23         node1.val = node2.val;24         node2.val = tem;25     }26 }

 

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.