标签:
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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
BST:二叉查找树。根节点大于左子树所有节点,根节点小于右子树所有节点。递归定义
题意
一棵BST中有两个节点交换了,恢复这颗树
思路
1.O(N)空间复杂度
中序遍历将节点放到list中,遍历list放到int[]数组中,对int[]数组进行排序,遍历list。list.get(i).val = nums[i]
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 import java.util.ArrayList; 11 import java.util.Arrays; 12 import java.util.List; 13 14 public class Solution { 15 List<TreeNode> listOfInOrder = new ArrayList<TreeNode>(); 16 17 public void recoverTree(TreeNode root) { 18 inOrderTravel(root); 19 int nums[] = new int[listOfInOrder.size()]; 20 for(int i = 0; i < nums.length; i++){ 21 nums[i] = listOfInOrder.get(i).val; 22 }//for 23 24 Arrays.sort(nums); //对数组升序排列 25 for(int i = 0; i < nums.length; i++) 26 listOfInOrder.get(i).val = nums[i]; 27 } 28 29 /** 30 * 中序遍历,节点放到list中 31 * @param root 32 */ 33 private void inOrderTravel(TreeNode root){ 34 if(root != null){ 35 inOrderTravel(root.left); 36 listOfInOrder.add(root); 37 inOrderTravel(root.right); 38 } 39 } 40 }
标签:
原文地址:http://www.cnblogs.com/luckygxf/p/4272773.html