输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def compareTree(self,inOrder,sequence): 4 n = len(sequence) 5 if n == 0: 6 return True 7 if n == 1: 8 return True if inOrder[0] == sequence[0] else False 9 root1 = sequence[-1] 10 for i in range(n): 11 if inOrder[i] == root1: 12 break 13 in1 = inOrder[:i] 14 last1 = sequence[:i] 15 16 in2 = inOrder[i+1:] 17 last2 = sequence[i:n-1] 18 return self.compareTree(in1,last1) and self.compareTree(in2,last2) 19 20 21 def VerifySquenceOfBST(self, sequence): 22 n = len(sequence) 23 if n == 0: 24 return False 25 inOrder = sorted(sequence) 26 root1 = sequence[-1] 27 for i in range(n): 28 if inOrder[i] == root1: 29 break 30 in1 = inOrder[:i] 31 last1 = sequence[:i] 32 33 in2 = inOrder[i+1:] 34 last2 = sequence[i:n-1] 35 return self.compareTree(in1,last1) and self.compareTree(in2,last2) 36 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 public boolean compareTree(int[] inorder, int[] postorder) { 3 int n = postorder.length; 4 if (n == 0) { 5 return true; 6 } 7 if (n == 1) { 8 return inorder[0] == postorder[0]; 9 } 10 int root1 = postorder[n - 1]; 11 int i = 0; 12 for (int j = 0; j < n; j++) { 13 if (inorder[j] == root1) { 14 i = j; 15 break; 16 } 17 } 18 19 int[] in1 = Arrays.copyOfRange(inorder, 0, i); 20 int[] last1 = Arrays.copyOfRange(postorder, 0, i); 21 22 int[] in2 = Arrays.copyOfRange(inorder, i + 1, n); 23 int[] last2 = Arrays.copyOfRange(postorder, i, n - 1); 24 25 return compareTree(in1, last1) && compareTree(in2, last2); 26 } 27 28 public boolean verifyPostorder(int[] postorder) { 29 int n = postorder.length; 30 if (n == 0) { 31 return true;//leetoce的判断,空数组返回true 32 } 33 int[] inorder = Arrays.copyOf(postorder, n); 34 Arrays.sort(inorder); 35 int root1 = postorder[n - 1]; 36 int i = 0; 37 for (int j = 0; j < n; j++) { 38 if (inorder[j] == root1) { 39 i = j; 40 break; 41 } 42 } 43 int[] in1 = Arrays.copyOfRange(inorder, 0, i); 44 int[] last1 = Arrays.copyOfRange(postorder, 0, i); 45 46 int[] in2 = Arrays.copyOfRange(inorder, i + 1, n); 47 int[] last2 = Arrays.copyOfRange(postorder, i, n - 1); 48 49 return compareTree(in1, last1) && compareTree(in2, last2); 50 } 51 }
思路分析:二叉树搜索树的中序遍历是有序的。因此对于一个二叉树的后序遍历顺序进行排序,就可以得到其中序遍历的结果。
使用中序遍历和后续遍历可以确定一棵二叉树。