[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 楠岃瘉浜屽弶鎼滅储鏍戠殑鍏堝簭搴忓垪
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 楠岃瘉浜屽弶鎼滅储鏍戠殑鍏堝簭搴忓垪相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/%e6%9c%89%e5%ba%8f%e6%95%b0%e7%bb%84' title='鏈夊簭鏁扮粍'>鏈夊簭鏁扮粍
exit .com blog btree ali title code etcGiven an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
Follow up:
Could you do it using only constant space complexity?
缁欎竴涓暟缁勶紝楠岃瘉鏄惁涓轰竴涓簩鍙夋悳绱㈡爲鐨勫厛搴忛亶鍘嗗嚭鐨勫簭鍒椼€?/p>
浜屽弶鏍戠殑鐗圭偣鏄細宸?lt;鏍?lt;鍙筹紝濡傛灉鐢ㄤ腑搴忛亶鍘嗗緱鍒扮殑缁撴灉灏辨槸鏈夊簭鏁扮粍锛岃€屽厛搴忛亶鍘嗙殑缁撴灉灏变笉鏄湁搴忔暟缁勩€?/p>
Python:
# Time: O(n) # Space: O(h) class Solution2: # @param {integer[]} preorder # @return {boolean} def verifyPreorder(self, preorder): low = float("-inf") path = [] for p in preorder: if p < low: return False while path and p > path[-1]: low = path[-1] path.pop() path.append(p) return True
Python:銆€銆€
# Time: O(n) # Space: O(1) class Solution: # @param {integer[]} preorder # @return {boolean} def verifyPreorder(self, preorder): low, i = float("-inf"), -1 for p in preorder: if p < low: return False while i >= 0 and p > preorder[i]: low = preorder[i] i -= 1 i += 1 preorder[i] = p return True
C++:
// Time: O(n) // Space: O(h) class Solution2 { public: bool verifyPreorder(vector<int>& preorder) { int low = INT_MIN; stack<int> path; for (auto& p : preorder) { if (p < low) { return false; } while (!path.empty() && p > path.top()) { // Traverse to its right subtree now. // Use the popped values as a lower bound because // we shouldn鈥榯 come across a smaller number anymore. low = path.top(); path.pop(); } path.emplace(p); } return true; } };
C++:
// Time: O(n) // Space: O(1) class Solution { public: bool verifyPreorder(vector<int>& preorder) { int low = INT_MIN, i = -1; for (auto& p : preorder) { if (p < low) { return false; } while (i >= 0 && p > preorder[i]) { low = preorder[i--]; } preorder[++i] = p; } return true; } };
銆€銆€
銆€銆€
绫讳技棰樼洰锛?/p>
[LeetCode] 144. Binary Tree Preorder Traversal 浜屽弶鏍戠殑鍏堝簭閬嶅巻
[LeetCode] 98. Validate Binary Search Tree 楠岃瘉浜屽弶鎼滅储鏍?/a>
銆€銆€
以上是关于[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 楠岃瘉浜屽弶鎼滅储鏍戠殑鍏堝簭搴忓垪的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 楠岃瘉浜屽弶鎼滅储鏍戠殑鍏堝簭搴忓垪
255. Verify Preorder Sequence in Binary Search Tree
255. Verify Preorder Sequence in Binary Search Tree
LeetCode Verify Preorder Sequence in Binary Search Tree