LeetCode 53 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?
分析:
この問題は二叉ルックアップツリーの性質を明確にしなければならない:中序遍歴は秩序がある.
したがって、隣接する2つの要素を比較することによって実現できる、自分の位置にない2つの要素を見つけて値を交換する必要があります.
2つのケースに分けられます.
1、2つの異常要素が隣接しており、1回の逆シーケンスしか現れません.
2,2つの異常要素が隣接していないと,2回の逆順が現れ,1回目の逆順の前に異常があり,2回目の逆順の後ろに異常がある(これはどのように証明するか分からないが,例を挙げるだけで分かる).
したがって、ツリーを中順に遍歴し、2つの異常要素ポインタを記録すればよい.
次は私のコードです.この文章を参考にして書いたのです.リンクをください.
この書き方はポインタが3つしか使われていないように見えますが、再帰するたびに空間が使われ、たぶんlog(n)なので定数空間でもありません.
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?
分析:
この問題は二叉ルックアップツリーの性質を明確にしなければならない:中序遍歴は秩序がある.
したがって、隣接する2つの要素を比較することによって実現できる、自分の位置にない2つの要素を見つけて値を交換する必要があります.
2つのケースに分けられます.
1、2つの異常要素が隣接しており、1回の逆シーケンスしか現れません.
2,2つの異常要素が隣接していないと,2回の逆順が現れ,1回目の逆順の前に異常があり,2回目の逆順の後ろに異常がある(これはどのように証明するか分からないが,例を挙げるだけで分かる).
したがって、ツリーを中順に遍歴し、2つの異常要素ポインタを記録すればよい.
次は私のコードです.この文章を参考にして書いたのです.リンクをください.
この書き方はポインタが3つしか使われていないように見えますが、再帰するたびに空間が使われ、たぶんlog(n)なので定数空間でもありません.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode pre;
TreeNode first;
TreeNode second;
public void recoverTree(TreeNode root) {
pre = first = second = null;
inorder(root);
if(first != null && second != null){
int temp = first.val;
first.val = second.val;
second.val = temp;
}
}
public void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
if(pre == null)
pre = root;
else{
if(pre.val > root.val){
//first null
// ,
if(first == null)
first = pre;
// second=root,
// , ,second
// , ,second
second = root;
}
pre = root;
}
inorder(root.right);
}
}