(劍指offer)重建二叉樹

2021-08-08 07:21:53 字數 881 閱讀 6702

題目描述:

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。

**如下:

public

class reconstructbinarytree

root = constructbinarytree(pre, 0, pre.length - 1, in, 0, in.length - 1);

return root;

}public treenode constructbinarytree(int pre, int prestr, int preend, int in, int instr, int inend)

// 前序遍歷的第乙個結點為二叉樹的根節點

treenode root = new treenode(pre[prestr]);

// 記錄每次根節點所在位置

int index = 0;

for (; index < inend; index++)

}// 遞迴呼叫求得根節點的左子樹

root.left = constructbinarytree(pre, prestr + 1, prestr + index - instr,

in, instr, index - 1);

// 遞迴呼叫求得根節點的右子樹

root.right = constructbinarytree(pre, prestr + index - instr + 1, preend,

in, index + 1, inend);

return root;

}}

劍指offer 重建二叉樹

重建二叉樹2.cpp 定義控制台應用程式的入口點。題目描述 輸入乙個二叉樹的前序遍歷和中序遍歷,輸出這顆二叉樹 思路 前序遍歷的第乙個節點一定是這個二叉樹的根節點,這個節點將二叉樹分為左右子樹兩個部分,然後進行遞迴求解 include stdafx.h include vector using na...

《劍指offer》重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如,則重建二叉樹並返回。輸入乙個樹的前序和中序,例如輸入前序遍歷序列和中序遍歷序列 根據輸入的前序和中序,重建乙個該二叉樹,並返回該樹的根節點。definition for binary...

劍指offer 重建二叉樹

題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。definition for binary tree struct treenode class solution if ...