[Leetcode][第99题][JAVA][恢复二叉搜索树][中序遍历]
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第99题][JAVA][恢复二叉搜索树][中序遍历]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【問題描述】[困難]
【解答思路】
1. 顯示中序遍歷
時間復雜度:O(N) 空間復雜度:O(N)
class Solution {public void recoverTree(TreeNode root) {List<Integer> nums = new ArrayList<Integer>();inorder(root, nums);int[] swapped = findTwoSwapped(nums);recover(root, 2, swapped[0], swapped[1]);}public void inorder(TreeNode root, List<Integer> nums) {if (root == null) {return;}inorder(root.left, nums);nums.add(root.val);inorder(root.right, nums);}public int[] findTwoSwapped(List<Integer> nums) {int n = nums.size();//第一次找到取前面 第二次找到取后面int x = -1, y = -1;for (int i = 0; i < n - 1; ++i) {if (nums.get(i + 1) < nums.get(i)) {y = nums.get(i + 1);if (x == -1) {x = nums.get(i);} else {break;}}}return new int[]{x, y};}public void recover(TreeNode root, int count, int x, int y) {if (root != null) {if (root.val == x || root.val == y) {root.val = root.val == x ? y : x;if (--count == 0) {return;}}recover(root.right, count, x, y);recover(root.left, count, x, y);}} }2. 隱式中序遍歷 棧
時間復雜度:O(N) 空間復雜度:O(H)
3. Morris 中序遍歷
時間復雜度:O(N) 空間復雜度:O(1)
【總結】
1. 交換的思想
兩個指針或兩個標志找逆序
2. 二叉搜索樹 中序遍歷 單調遞增
3.空間復雜度優化 Morris 中序遍歷優化 空間復雜度:O(1)
轉載鏈接:https://leetcode-cn.com/problems/recover-binary-search-tree/solution/hui-fu-er-cha-sou-suo-shu-by-leetcode-solution/
總結
以上是生活随笔為你收集整理的[Leetcode][第99题][JAVA][恢复二叉搜索树][中序遍历]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下编译opendds,Linu
- 下一篇: 人工鱼群算法Matlab实现