劍指offer 面試題6 重建二叉樹

2021-08-10 10:53:18 字數 1390 閱讀 4937

package chapter2;

/** * 面試題6:重建二叉樹

* 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。

* 假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。

* 例如輸入前序遍歷序列和中序遍歷序列,

* 或者輸入後序遍歷序列和中序遍歷序列則重建二叉樹。

*/public class _06_binarytree ;

int in = ;

int post = ; // 後序遍歷

_06_function f = new _06_function();

_06_function.treenode res1 = f.createtree(pre, 0, pre.length - 1, in, 0, in.length - 1);

_06_function.treenode res2 = f.createtreebyinnpost(in, 0, in.length - 1, post, 0, post.length - 1);

system.out.println("**********====前,中***************");

f.preorder(res1);

system.out.println();

f.inorder(res1);

system.out.println();

f.postorder(res1);

system.out.println();

system.out.println("**********====中,後***************");

f.preorder(res2);

system.out.println();

f.inorder(res2);

system.out.println();

f.postorder(res2); }}

class _06_function

} treenode createtree(int pre, int pre_start, int pre_end, int in, int in_start, int in_end)

} return tree_node;

} treenode createtreebyinnpost(int in, int in_start, int in_end, int post, int post_start, int post_end)

} return tree_node;

} void preorder(treenode node)

} void inorder(treenode node)

} void postorder(treenode node)

}}

劍指offer 面試題6 重建二叉樹

題目 輸入某二叉樹的前序遍歷和中序遍歷,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含有重複的數字。例如,前序遍歷序列 1,2,4,7,3,5,6,8 中序遍歷序列 4,7,2,1,5,3,8,6 則重建出的二叉樹如下所示,並輸出它的頭結點1。基本思想 前序遍歷 前序遍歷首先訪問根結點...

劍指offer《面試題6 重建二叉樹》

題目 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建出下圖所示的二叉樹並輸出它的頭結點。1 2 3 4 5 6 7 8 劍指offer 名企面試官精講典型程式設計題 著作權所有者 何海濤 inc...

劍指offer 面試題6重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。重建出二叉樹,並輸出根節點。二叉樹的定義如下 如上,前序遍歷 1,2,4,7,3,5,6,8,中序 4,7,2,1,5,3,8,6,後序遍歷 7,4,2,5,8,6,3,1 在二叉樹的前序...