leetcode第50題(recover-binary-search-tree)
阿新 • • 發佈:2019-01-31
題目:
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:A solution using O(n ) space is pretty straight forward. Could you devise a constant space solution?
思路:
中序遍歷找到發生錯誤的兩個節點,並記錄下節點,最後交換這兩個節點的值即可。pre代表前序遍歷的前一個節點,mistake1和mistake2是兩個錯誤的節點。判斷出錯的依據是當前節點的值大於pre節點的值。
程式碼:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { TreeNode pre,mistake1,mistake2; public void recoverTree(TreeNode root) { inTraversal(root); inttemp=mistake1.val; mistake1.val = mistake2.val; mistake2.val = temp; } public void inTraversal(TreeNode root){ if(root==null) return ; inTraversal(root.left); if(pre!=null&&pre.val>root.val){ if(mistake1==null){ mistake1=pre; mistake2=root; }else mistake2=root; } pre=root; inTraversal(root.right); } }