1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #include <bits/stdc++.h> using namespace std;void change (string pre, string inor) { if (pre.empty ())return ; char root = pre[0 ]; pre.erase (pre.begin ()); int k = inor.find (root); string leftinor = inor.substr (0 , k); string rightinor = inor.substr (k + 1 ); string leftpre = pre.substr (0 , k); string rightpre = pre.substr (k); change (leftpre, leftinor); change (rightpre, rightinor); cout << root; }int main () { string pre, inor; cin >> inor >> pre; change (pre, inor); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Codec : def serialize (self, root: Optional [TreeNode] ) -> str : """Encodes a tree to a single string. """ arr = [] def postOrder (root ): if root is None : return postOrder(root.left) postOrder(root.right) arr.append(root.val) postOrder(root) return ' ' .join(map (str ,arr)) def deserialize (self, data: str ) -> Optional [TreeNode]: """Decodes your encoded data to tree. """ arr = list (map (int , data.split())) def construct (lower,upper ): if arr == [] or arr[-1 ] < lower or arr[-1 ] > upper: return None val = arr.pop() root = TreeNode(val) root.right = construct(val, upper) root.left = construct(lower,val) return root return construct(-inf,inf)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class Codec : def serialize (self, root ): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root is None : return 'None' return str (root.val) + ',' + str (self.serialize(root.left)) + ',' + str (self.serialize(root.right)) def deserialize (self, data ): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ def dfs (dataList ): val = dataList.pop(0 ) if val == 'None' : return None root = TreeNode(int (val)) root.left = dfs(dataList) root.right = dfs(dataList) return root dataList = data.split(',' ) return dfs(dataList)
很经典的二叉树 搜索问题 分为三步 1 判断根节点 2判断叶子节点 3递归左右 同时变化条件(limit)
这个题关键就是 看出来 只有左右都不满足的时候 (把左右都删掉)根才能不满足 如果左右没删除 说明有满足大于limit的 那么根必定是有大于limit的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class Solution {public : TreeNode* sufficientSubset (TreeNode* root, int limit) { if (root == nullptr ) return nullptr ; if (root->left == nullptr && root->right == nullptr ) { if (limit > 0 ) root = nullptr ; return root; } if (root->left) root->left = sufficientSubset (root->left, limit - root->val); if (root->right) root->right = sufficientSubset (root->right, limit - root->val); if (root->left == nullptr && root->right == nullptr )return nullptr ; else return root; } };