首頁  >  文章  >  Java  >  java中如何實作重建二元樹

java中如何實作重建二元樹

王林
王林轉載
2019-11-28 15:53:351941瀏覽

java中如何實作重建二元樹

主題:輸入某二元樹的前序遍歷和中序遍歷的結果,請重建出該二元樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}及中序遍歷序列{4,7,2,1,5,3,8,6},則重建二元樹並返回。

解法分析:

1.根據前序遍歷首節點決定根節點。

2.找到中序遍歷中的根節點,決定左子樹長度和右子樹長度。

3.依長度,在前序遍歷中取左子樹前序遍歷和右子樹前序遍歷,在中序遍歷中取左子樹中序遍歷和右子樹中序遍歷

4.遞歸左子樹和右子樹,並將左子樹根節點和右子樹根節點賦到根節點上。

免費影片教學推薦:java學習

程式碼:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre.length == 0 || in.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(pre[0]);
        for(int i = 0 ; i < in.length; i++) {
            if(in[i] == pre[0]) {
                root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
                root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length)
                ,Arrays.copyOfRange(in,i+1,in.length));
            }
        }
        return root;
    }
}

更多相關文章教學推薦:java程式設計入門

以上是java中如何實作重建二元樹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除