Recover Binary Search Tree--leetcode難題講解

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?ios

https://leetcode.com/problems/recover-binary-search-tree/git

二叉排序樹中有兩個節點被交換了,要求把樹恢復成二叉排序樹。github

最簡單的辦法,中序遍歷二叉樹生成序列,而後對序列中排序錯誤的進行調整。最後再進行一次賦值操做,但這個不符合空間複雜度要求。app

須要用兩個指針記錄錯誤的那兩個元素,而後進行交換。spa

怎樣找出錯誤的元素?遍歷二叉排序樹,正確時應該是從小到大,若是出現以前遍歷的節點比當前大,則說明出現錯誤。因此咱們須要一個pre指針來指向以前通過的節點。指針

若是隻有一處不符合從小到大,則只用交換這一個地方。第二個指針記錄第二個異常點。code

 

 Github repository: https://github.com/huashiyiqike/myleetcode blog

//JAVA CODE:
public
class Solution { TreeNode first = null, second = null, pre = null; //first larger than follow, second smaller than pre public void helper(TreeNode root){ if(root.left != null) helper(root.left); if(pre != null && root.val < pre.val){ if(first == null) first = pre; second = root; } pre = root; if(root.right != null) helper(root.right); } public void recoverTree(TreeNode root) { helper(root); int tmp = first.val; first.val = second.val; second.val = tmp; } }

 

//C++ CODE:
#include <iostream> #include <cstdlib> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { TreeNode *first = NULL, *second = NULL, *last = NULL; public: void inorder(TreeNode* root){ if(root->left != NULL){ inorder(root->left); } if(last != NULL && root->val < last->val){ if(first == NULL) first = last; second = root; } last = root; if(root->right != NULL) inorder(root->right); } void recoverTree(TreeNode* root) { if(root == NULL) return; inorder(root); if(first && second) std::swap(first->val, second->val); } };
#PYTHON CODE:
class
Solution: def inorderTravel(self, root, last): if root.left: last = self.inorderTravel(root.left, last) if last and last.val > root.val: if self.first is None: self.first = last self.second = root last = root if root.right: last = self.inorderTravel(root.right, last) return last def recoverTree(self, root): if root is None: return self.first, self.second = None, None self.inorderTravel(root, None) self.first.val, self.second.val = self.second.val, self.first.val
相關文章
相關標籤/搜索