Leetcode 99. Recover Binary Search Tree
Posted zhangwj0101
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 99. Recover Binary Search Tree相关的知识,希望对你有一定的参考价值。
Question
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Code
TreeNode pre = null;
TreeNode first = null;
TreeNode second = null;
public void recoverTree(TreeNode root)
inOrder(root);
int tmp = first.val;
first.val = second.val;
second.val = tmp;
public void inOrder(TreeNode root)
if (root == null)
return;
inOrder(root.left);
if (pre != null && pre.val > root.val)
if (first == null)
first = pre;
second = root;
else
second = root;
pre = root;
inOrder(root.right);
以上是关于Leetcode 99. Recover Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章