<span style="font-size:18px;">/* * LeetCode: recover the binary search tree * 题目:二叉树中有两个节点被交换了位置,找出它们,并且将它们换回来,要求用o(n)的连续空间 * 知识点:1、BST树的特点:中序遍历后的节点的排列是按照非降的顺序 * 思路:按照特点中序遍历,当遇到逆序的节点则按照保存相关节点,注意分为,交换的两个点是否相邻的两种情况 */ package javaTrain; public class Train6 { public TreeNode firstNode = null,preNode = null,secondNode = null; public int preVal = Integer.MIN_VALUE; public void recoverTree(TreeNode root) { if(root == null) return; findInChild(root); int temp = firstNode.val; firstNode.val = secondNode.val; secondNode.val = temp; return; } private void findInChild(TreeNode root){ if(root == null) return; findInChild(root.left); if(root.val < preVal){ if(firstNode == null){ firstNode = preNode; secondNode = root; } else{ secondNode = root; return; } } preNode = root; preVal = root.val; findInChild(root.right); } } </span>
时间: 2024-10-21 12:21:11