二叉搜索树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。示例 1:输入: [1,3,null,null,2]1/3\2输出: [3,1,null,null,2]3/1\2
代码
/*** 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 {PriorityQueue<Integer> treeNodes=new PriorityQueue<>();public void recoverTree(TreeNode root) {mid(root);midd(root);}public void midd(TreeNode root) {//中序遍历,将优先队列中生成正确的顺序装回树上if(root==null) return;midd(root.left);root.val=treeNodes.poll();midd(root.right);}public void mid(TreeNode root) {//中序遍历,并在优先队列中生成正确的顺序if(root==null) return;mid(root.left);treeNodes.add(root.val);mid(root.right);}
}