099 Recover Binary Search Tree 复原二叉搜索树
二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。
详见:https://leetcode.com/problems/recover-binary-search-tree/submissions/
Java实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public void recoverTree(TreeNode root) { List<TreeNode> node=new ArrayList<TreeNode>(); List<Integer> val=new ArrayList<Integer>(); inOrder(root,node,val); Collections.sort(val); for(int i=0;i<node.size();++i){ if(node.get(i).val!=val.get(i)){ node.get(i).val=val.get(i); } } } private void inOrder(TreeNode root,List<TreeNode> node,List<Integer> val){ if(root==null){ return; } inOrder(root.left,node,val); node.add(root); val.add(root.val); inOrder(root.right,node,val); } }