C++由数组构建二叉树指针
种一棵二叉树最好的时间是十年前,其次是现在😄。
先讲一下前序、中序、后序遍历,
其实就是(访问当前节点的值的代码cout<<(root->val)<<endl;
)与递归代码(递归左右节点)位置关系来区分
二叉树遍历类型
前序遍历
{//前序遍历
if (root==nullptr) return;
cout<<(root->val)<<endl;//先访问当前节点
showBranch(root->left);
showBranch(root->right);
}
中序遍历
{//中序遍历
if (root==nullptr) return;
showBranch(root->left);
cout<<(root->val)<<endl;//访问完左节点再访问当前节点
showBranch(root->right);
}
后序遍历
{//后序遍历
if (root==nullptr) return;
showBranch(root->left);
showBranch(root->right);
cout<<(root->val)<<endl;//最后访问当前节点
}
简单实现把数组换成指针然后前序遍历
#include <iostream>
using namespace std;
struct TreeNode {//定义树节点
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// new a tree
TreeNode *newTree(int list[],int lt,int i=0){//种树
if(i>=lt) return nullptr;
TreeNode *t=new TreeNode(list[i]);
t->left=newTree(list,lt,2*i+1);
t->right=newTree(list,lt,2*i+2);
return t;
}
void showBranch(TreeNode *root){//前序遍历
if (root==nullptr) return;
root->val==NULL?cout<<("x")<<endl:cout<<(root->val)<<endl;//空节点用x表示
showBranch(root->left);
showBranch(root->right);
}
//
int main(){
TreeNode *root;
int List[]={120,70,140,50,100,130,160,20,55,75,110,119,135,150,NULL};
int lt=sizeof(List)/sizeof(List[0]);
showBranch(newTree(List,lt));
// getchar();
}