Leetcode: Recover Binary Search Tree
2015-01-28 04:10
453 查看
Problem:
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?
confused what
read more on how binary tree is serialized on OJ.
Solution:
Using Inorder Traverse.
Code
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode p;
TreeNode q;
TreeNode tmp = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
if (root == null) return;
recover(root);
if (p != null && q != null) {
int t = p.val;
p.val = q.val;
q.val = t;
}
}
public void recover(TreeNode root) {
if (root == null) return;
recover(root.left);
if (tmp != null && root.val < tmp.val) {
if(p == null) {
p = tmp;
q = root;
} else {
q = root;
}
}
tmp = root;
recover(root.right);
}
}
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?
confused what
"{1,#,2,3}"means? >
read more on how binary tree is serialized on OJ.
Solution:
Using Inorder Traverse.
Code
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode p;
TreeNode q;
TreeNode tmp = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
if (root == null) return;
recover(root);
if (p != null && q != null) {
int t = p.val;
p.val = q.val;
q.val = t;
}
}
public void recover(TreeNode root) {
if (root == null) return;
recover(root.left);
if (tmp != null && root.val < tmp.val) {
if(p == null) {
p = tmp;
q = root;
} else {
q = root;
}
}
tmp = root;
recover(root.right);
}
}
相关文章推荐
- Leetcode:Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- leetcode: Recover Binary Search Tree
- Leetcode Recover Binary Search Tree
- leetcode Recover Binary Search Tree
- leetcode:Recover Binary Search Tree (修正二叉查找树错误节点,不改变结构)【面试算法题】
- [LeetCode] Recover Binary Search Tree
- 【LeetCode】Recover Binary Search Tree
- leetcode99---Recover Binary Search Tree(morris中序遍历恢复BST)
- LeetCode: Recover Binary Search Tree
- [leetcode] Recover Binary Search Tree
- Recover Binary Search Tree leetcode java
- LeetCode Recover Binary Search Tree
- leetcode:Recover Binary Search Tree 【Java】
- [leetcode] recover binary search tree
- [LeetCode]Recover Binary Search Tree
- Recover Binary Search Tree -- LeetCode
- LeetCode99 Recover Binary Search Tree
- 【Leetcode】Recover Binary Search Tree
- Recover Binary Search Tree - LeetCode