算法记录
LeetCode 题目:
给你二叉搜索树的根节点 root
,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树 。
说明
一、题目
输入:root = [1,3,null,null,2]
输出:[3,1,null,null,2]
解释:3 不能是 1 的左孩子,因为 3 > 1 。交换 1 和 3 使二叉搜索树有效。
二、分析
- 二叉搜索树中间出现了两个节点错误,那我们就只需要遍历整个树就会得到一个序列节点。
- 再次遍历这个序列节点,只要违背了序列递增的就将两个位置记录下来。
- 而且这两个节点位置可能不是挨在一起的,因此需要判断一下,第一次的冲突需要记录两个,因为这是其中一种挨在一起的情况。后面出现的冲突只需要记录第二个节点即可,因为第一个错误已经确定了。
class Solution {
public void recoverTree(TreeNode root) {
List<TreeNode> temp = new ArrayList();
dfs(root, temp);
TreeNode one = null, two = null;
for(int i = 1; i < temp.size(); i++) {
if(temp.get(i - 1).val > temp.get(i).val) {
if(one == null) {
one = temp.get(i - 1);
two = temp.get(i);
continue;
}
two = temp.get(i);
break;
}
}
int t = one.val;
one.val = two.val;
two.val = t;
}
public void dfs(TreeNode root, List<TreeNode> temp) {
if(root == null) return;
dfs(root.left, temp);
temp.add(root);
dfs(root.right, temp);
}
}
总结
二叉搜索树的性质。