0
点赞
收藏
分享

微信扫一扫

二叉树构建、删除、遍历、求深度、求节点数



//Notice: this file.cpp can run on your pc;
//input: example
// 1
// 2 3
// you can input 1 2 0 0 3 0 0
// then you'll get a binaryTree like line 3、4

#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct BinaryTreeNode{
int data;
BinaryTreeNode *left;
BinaryTreeNode *right;
}BinaryTreeNode;


BinaryTreeNode* createBinaryTree(){
BinaryTreeNode *p;
int a;
cin >> a;
if(a==0){
p = NULL;
}else{
p = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode));
p->data = a;
p->left = createBinaryTree();
p->right = createBinaryTree();
}

return p;


}


void preOrder(BinaryTreeNode *root){
if(root == NULL) return;
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}



void postOrder(BinaryTreeNode *root){
if(root == NULL) return;
postOrder(root->left);
postOrder(root->right);
cout << root->data << " ";
}


void inOrder(BinaryTreeNode *root){
if(root == NULL) return;
inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}

int numberBTN(BinaryTreeNode *root){
if(root == NULL)
return 0;
return 1 + numberBTN(root->left) + numberBTN(root->right);
}

int numberBTLN(BinaryTreeNode *root){
if(root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1; //不同于上一个统计全部节点数目,这回只有叶子节点才统计
return numberBTLN(root->left) + numberBTLN(root->right);
}



/*
you can also use another method just like:
int numberNotBTLN(BinaryTreeNode *root){
return numberBTN(root) - numberBTLN(root);
}
*/
int numberNotBTLN(BinaryTreeNode *root){
if(root == NULL)
return 0;
if(root->left != NULL || root->right != NULL)
return 1;
return numberBTLN(root->left) + numberBTLN(root->right);
}

int depthBT(BinaryTreeNode *root){
if(root == NULL)
return 0;
int leftHeight = depthBT(root->left);
int rightHeight = depthBT(root->right);

return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}

void deleteBT(BinaryTreeNode *root){
if(root == NULL)
return;
deleteBT(root->left);
deleteBT(root->right);
free(root);
root = NULL;
}

main(){
BinaryTreeNode *root = NULL;
root = createBinaryTree();

cout << "preOrder:";
preOrder(root);
cout << endl;

cout << "inOrder:";
inOrder(root);
cout << endl;

cout << "postOrder:";
postOrder(root);
cout << endl;

cout << "numberBTN:";
cout << numberBTN(root);
cout << endl;

cout << "numberBTLN:";
cout << numberBTLN(root);
cout << endl;

cout << "numberBTLN:";
cout << numberNotBTLN(root);
cout << endl;

cout << "depthBT:";
cout << depthBT(root);
cout << endl;

deleteBT(root);

}

 

 

举报

相关推荐

0 条评论