码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Recover Binary Search Tree

时间:2014-07-31 23:13:00      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   io   for   ar   

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. Could you devise a constant space solution? 

 

算法思路:

思路1:求出中序遍历序列,空间复杂度O(n),tip要求只可以开O(1)空间。

代码略

思路2:中序遍历,遇到每个点,都记录其前驱,记录当前指针cur的前一个节点pre,如果pre.val大于cur.val,表示有错序,多数情况错序有两次;如果有一次错序,说明就是相邻节点需要被交换。

 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 }

 

[leetcode]Recover Binary Search Tree,布布扣,bubuko.com

[leetcode]Recover Binary Search Tree

标签:style   blog   http   color   strong   io   for   ar   

原文地址:http://www.cnblogs.com/huntfor/p/3881570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!