标签:
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.
Here‘s an example:
1 / 2 3 / 4 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.思路:我们都知道中序遍历树的话就会是一个递增的序列,那么如果交换的节点刚好相邻的话,那么我们记录然后交换一下就行了,但是如果两个数是不相邻的话,比如说:12345,交换了1和5,->52341,那么这个序列就存在了两个逆序对,52,和41,那么我们记录第一次出现的第一个,第二次出现的第二个,也就是5和1,那么交换就行了。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private TreeNode preNode = null; private void cal(TreeNode root, List<TreeNode> res) { if (root == null) return; cal(root.left, res); if (preNode != null && preNode.val > root.val) { if (res.size() == 0) { res.add(preNode); res.add(root); } else { res.set(1, root); } } preNode = root; cal(root.right, res); } public void recoverTree(TreeNode root) { if (root == null) return; List<TreeNode> res = new ArrayList<TreeNode>(); cal(root, res); if (res.size() > 0) { int tmp = res.get(0).val; res.get(0).val = res.get(1).val; res.get(1).val = tmp; } } }
LeetCode Recover Binary Search Tree
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45273973