码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 099 Recover Binary Search Tree

时间:2015-05-22 01:49:49      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

解题思路:

先中序遍历找到mistake,然后替换即可,JAVA实现如下:

public void recoverTree(TreeNode root) {
		List<Integer> list = inorderTraversal(root);
		int left = 0, right = 0;
		boolean first = true;
		for (int i = 0; i < list.size(); i++) {
			if (first && i != list.size() - 1 && list.get(i) >= list.get(i + 1)) {
				left = list.get(i);
				first = false;
			}
			if (!first && i != 0 && list.get(i) < list.get(i - 1)) {
				right = list.get(i);
			}
		}
		transformTreeNode(root, right, Integer.MAX_VALUE);
		transformTreeNode(root, left, right);
		transformTreeNode(root, right, left);

	}

	public static void transformTreeNode(TreeNode root, int souce, int target) {
		if (root == null)
			return;
		if (root.val == souce) {
			root.val = target;
			return;
		}
		transformTreeNode(root.left, souce, target);
		transformTreeNode(root.right, souce, target);
	}

	static public List<Integer> inorderTraversal(TreeNode root) {
		List<Integer> list = new ArrayList<Integer>();
		if (root == null)
			return list;
		if (root.left != null)
			list.addAll(inorderTraversal(root.left));
		list.add(root.val);
		if (root.right != null)
			list.addAll(inorderTraversal(root.right));
		return list;
	}

 

Java for LeetCode 099 Recover Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4521226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!