P140、面试题24:二叉搜索树的后序遍历序列
题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。
测试用例:
1)功能测试(输入的后序遍历的序列对应一棵二叉树,包括完全二叉树,所有结点都没有左/右子树的二叉树、只有一个结点的二叉树;输入的后续遍历的序列没有对应一棵二叉树);
2)特殊输入测试(指向后序遍历序列的指针为null指针)。
代码实现:
package com.yyq; import java.util.Arrays; /** * Created by Administrator on 2015/9/20. */ public class SequenceOfBST { public static boolean verifySquenceOfBST(int sequence[], int length){ if (sequence == null || length <= 0) return false; int root = sequence[length-1]; //在二叉搜索树中左子树的结点小于根结点 int i = 0; for (;i < length-1; i++){ if (sequence[i] > root) break; } //在二叉搜索树中右子树的结点大于根节点 int j = i; for (; j < length-1; j++){ if (sequence[j] < root) return false; } //判断左子树是不是二叉搜索树 boolean left = true; if (i > 0) left = verifySquenceOfBST(sequence,i); //判断右子树是不是二叉搜索树 boolean right = true; if (i < length-1) { int[] temp = Arrays.copyOfRange(sequence, i, length-1); right = verifySquenceOfBST(temp, length-i-1); } return (left && right); } // ====================测试代码==================== public static void Test(String testName, int sequence[], int length, boolean expected) { if(testName != null) System.out.println(testName+" begins: " ); if(verifySquenceOfBST(sequence, length) == expected) System.out.println("passed."); else System.out.println("failed."); } // 10 // / \ // 6 14 // /\ /\ // 4 8 12 16 public static void Test1() { int data[] = {4, 8, 6, 12, 16, 14, 10}; Test("Test1", data, data.length, true); } // 5 // / \ // 4 7 // / // 6 public static void Test2() { int data[] = {4, 6, 7, 5}; Test("Test2", data, data.length, true); } // 5 // / // 4 // / // 3 // / // 2 // / // 1 public static void Test3() { int data[] = {1, 2, 3, 4, 5}; Test("Test3", data, data.length, true); } // 1 // \ // 2 // \ // 3 // \ // 4 // \ // 5 public static void Test4() { int data[] = {5, 4, 3, 2, 1}; Test("Test4", data, data.length, true); } // 树中只有1个结点 public static void Test5() { int data[] = {5}; Test("Test5", data, data.length, true); } public static void Test6() { int data[] = {7, 4, 6, 5}; Test("Test6", data, data.length, false); } public static void Test7() { int data[] = {4, 6, 12, 8, 16, 14, 10}; Test("Test7", data, data.length, false); } public static void Test8() { Test("Test8", null, 0, false); } public static void main(String[] args) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); Test8(); } }
结果输出:
Test1 begins:
passed.
Test2 begins:
passed.
Test3 begins:
passed.
Test4 begins:
passed.
Test5 begins:
passed.
Test6 begins:
passed.
Test7 begins:
passed.
Test8 begins:
passed.