判斷一個數組是否爲後序遍歷結果

輸入一個整數數組,判斷該數組是否是某二元查找樹的後序遍歷的結果。若是是返回true,不然返回false。
思路一:
中序遍歷爲增加數組,判斷是否矛盾
思路二:
如五、七、六、九、十一、十、8
代碼編寫具體思路:
1.找到第一個大於根節點的數,即9,因此9以後的爲右子樹
2.若是右子樹的值都大於根節點8,則符合
3.遞歸法分別判斷是否左子樹和右子樹都符合這種特色。java

package com.lifeibigdata.algorithms.blog;

import java.util.Arrays;

/**
 * 
 * 五、七、六、九、十一、十、8
 *      8
    /      \
   6       10
  / \     / \
 5   7   9  11

 */
public class SearchTree {
    public static void main(String[] args) {
//        int[] a = {5,7,6,9,11,10,8};  //true
        int a[] = {7, 4, 6, 5} ;     //false
        System.out.println(searchTree(a,a.length)) ;

    }
    static boolean searchTree(int[] a,int length){
        if (a == null || length <= 0){
            return false;
        }
        boolean flag = true;
        int root = a[length - 1];
        int i = 0;
        while (a[i] < root){
            i++;           //獲得左子樹和右子樹的分界線,a[i]爲右子樹第一個
        }
        int j = i;
        for (;j < length - 1; ++j){
            if (a[j] < root){
                flag = false;
            }
        }
        if (i > 0){
            searchTree(a,i);
        }
        if (i < length -1){
            searchTree(Arrays.copyOfRange(a,i,length -1),length -i - 1);
        }
        return flag;
    }
}
相關文章
相關標籤/搜索