力扣99.恢复二叉搜索树

99.恢复二叉搜索树

思路:

  1. 用数组或者链表收集 中序遍历的数值
  2. 记录 两个顺序错误的值
  3. 用HashMap,获取值错误的那个节点,交换节点的值即可

代码实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int problem1 = -1;
	int problem2 = -1;
	HashMap<Integer, TreeNode> map = new HashMap<>();
	public void recoverTree(TreeNode root) {
		TreeNode node1, node2, tmp;
        List<Integer> list = new LinkedList<Integer>();
        inorder(root, list);
        for (int i = 0; i < list.size() - 1; i++) {
        	if (list.get(i) > list.get(i + 1)) {
        		problem1 = list.get(i);
                break;
        	}
        }
        for (int i = list.size() - 1; i > 0; i--) {
        	if (list.get(i) < list.get(i - 1)) {
        		problem2 = list.get(i);
                break;
        	}
        }
        node1 = map.get(problem1);
        node2 = map.get(problem2);
        
        node1.val = problem2;
        node2.val = problem1;
       
    }
	
	public void inorder(TreeNode root, List<Integer> list) {
		if (root == null) return ;

		inorder(root.left, list);
		map.put(root.val, root);
		list.add(root.val);
		inorder(root.right, list);
	}
}

你可能感兴趣的:(leetcode,链表,数据结构)