[分析]
思路1:暴力法,遍历当前待检查数组,找到第一个大于数组起始位置的位置i,则 i 为右子树根节点,然后递归判断左右子树。对于根节点,最坏情况下要遍历整个数组,时间为O(N),因为要递归检查每个节点,因此总的时间复杂度是O(N^2)。
思路2:参考StefanPochmann大神的作品
https://leetcode.com/discuss/51543/java-o-n-and-o-1-extra-space, 时间复杂度是O(N),空间复杂度是O(h)。
public class Solution {
// Method 2
public boolean verifyPreorder(int[] preorder) {
if (preorder == null || preorder.length == 0) return true;
LinkedList<Integer> stack = new LinkedList<Integer>();
int low = Integer.MIN_VALUE;
for (int i = 0; i < preorder.length; i++) {
if (preorder[i] < low) return false;
while (!stack.isEmpty() && preorder[i] > stack.peek()) {
low = stack.pop();
}
stack.push(preorder[i]);
}
return true;
}
// Method 1: brute force
public boolean verifyPreorder1(int[] preorder) {
if (preorder == null) return false;
return recur(preorder, 0, preorder.length - 1);
}
public boolean recur(int[] preorder, int start, int end) {
if (start >= end) return true;
int i = start + 1;
while (i <= end && preorder[i] < preorder[start])
i++;
if (!recur(preorder, start + 1, i - 1))
return false;
int rightStart = i;
while (i <= end && preorder[i] > preorder[start])
i++;
if (i <= end) return false;
return recur(preorder, rightStart, end);
}
}
分享到:
相关推荐
java java_leetcode-105-construct-binary-tree-from-preorder-and-inorde
java java_leetcode-99-recover-binary-search-tree
java java_leetcode-110-balanced-binary-tree
java java_leetcode-114-flatten-binary-tree-to-linked-list
java java_leetcode-maximum-depth-of-binary-tree
java java_leetcode-111-minimum-depth-of-binary-tree
java java_leetcode-107-binary-tree-level-order-traversal
java java_leetcode-102-binary-tree-level-order-traversal
python python_leetcode_109_Convert_Sorted_List_to_Binary_Search_Tree
c语言入门 c语言_leetcode题解543-diameter-of-binary-tree.c
js js_leetcode题解之105-construct-binary-tree-from-preorder
java java_leetcode-101-symmetric-tree
java java_leetcode-100-same-tree
javascript js_leetcode题解之109-convert-sorted-list-to-binary-search-tree.js
js js_leetcode题解之108-convert-sorted-array-to-binary-search-tree.js
javascript js_leetcode题解之111-minimum-depth-of-binary-tree.js
js js_leetcode题解之104-maximum-depth-of-binary-tree.js
python python_leetcode题解之144_Binary_Tree_Preorder_Traversal
c语言入门 c语言_leetcode题解之1373_maximum_sum_bst_in_binary_tree
java java_leetcode题解之Distribute Coins in Binary Tree.java