輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。
typedef
struct treenode
tnode;
void preorder(tnode *node)
void inorder(tnode *node)
void posorder(tnode *node)
tnode* reconstructbinarytree(vector
pre,vector
in)
//求右子樹前序遍歷(preright)和中序遍歷(inright)
i++;
vector
preright;
vector
inright;
while(i < (int)in.size())
//重建左子樹
node->left = reconstructbinarytree(preleft,inleft);
//重建右子樹
node->right = reconstructbinarytree(preright,inright);
return node;
}
#include
#include
using
namespace
std;
int main(int argc, char **argv)
; vector
in = ;
tnode *pp =reconstructbinarytree(pre,in);
//前序遍歷
cout
<<"前序遍歷:";
preorder(pp);
cout
cout
<<"中序遍歷:";
inorder(pp);
cout
cout
<<"後序遍歷:";
posorder(pp);
cout
0;}
前序遍歷:1 2 4 7 3 5 6 8
中序遍歷:4 7 2 1 5 3 8 6
後序遍歷:7 4 2 5 8 6 3 1
劍指offer 重建二叉樹
重建二叉樹2.cpp 定義控制台應用程式的入口點。題目描述 輸入乙個二叉樹的前序遍歷和中序遍歷,輸出這顆二叉樹 思路 前序遍歷的第乙個節點一定是這個二叉樹的根節點,這個節點將二叉樹分為左右子樹兩個部分,然後進行遞迴求解 include stdafx.h include vector using na...
《劍指offer》重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如,則重建二叉樹並返回。輸入乙個樹的前序和中序,例如輸入前序遍歷序列和中序遍歷序列 根據輸入的前序和中序,重建乙個該二叉樹,並返回該樹的根節點。definition for binary...
劍指offer 重建二叉樹
題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。definition for binary tree struct treenode class solution if ...