Leetcode 99: 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?

 

Note: this solution beats 100% C# submissions.

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public void RecoverTree(TreeNode root) {
12         var candidates = new TreeNode[2];
13         DFS(root, new TreeNode[1], candidates);
14         if (candidates[0] != null && candidates[1] != null)
15         {
16             var tmp = candidates[0].val;
17             candidates[0].val = candidates[1].val;
18             candidates[1].val = tmp;
19         }
20     }
21     
22     private void DFS(TreeNode node, TreeNode[] prior, TreeNode[] candidates)
23     {
24         if (node == null) return;
25         
26         DFS(node.left, prior, candidates);
27         
28         if (prior[0] != null)
29         {
30             if (prior[0].val > node.val)
31             {
32                 if (candidates[0] == null)
33                 {
34                     candidates[0] = prior[0];
35                     candidates[1] = node;
36                 }
37                 else
38                 {
39                     candidates[1] = node;
40                 }
41             }
42         }
43         
44         prior[0] = node;
45         
46         DFS(node.right, prior, candidates);
47     }
48 }

 

 

 
posted @ 2017-11-15 05:57  逸朵  阅读(108)  评论(0)    收藏  举报