递归实现二叉树遍历
#include <iostream>
#include <algorithm>
using namespace std;
typedef struct Node{
int data;
Node* lchild,* rchild;
}Node;
Node* createNode(int data)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = data;
temp->lchild = temp->rchild = NULL;
return temp;
}
void setChild(Node* root, Node* lchild, Node* rchild)
{
root->rchild = rchild;
root->lchild = lchild;
}
void preorderTrav(Node* root)
{
if (root == NULL)
return;
cout << root->data<<" ";
preorderTrav(root->lchild);
preorderTrav(root->rchild);
}
void inorderTrav(Node* root)
{
if (root == NULL) return;
inorderTrav(root->lchild);
cout << root->data<<" ";
inorderTrav(root->rchild);
}
void pastorderTrav(Node* root)
{
if (root == NULL) return;
pastorderTrav(root->lchild);
pastorderTrav(root->rchild);
cout << root->data << " ";
}
int getTreeHeight(Node* root)
{
if (root == NULL) return 0;
int leftHeight = getTreeHeight(root->lchild);
int rightHeight = getTreeHeight(root->rchild);
return max(leftHeight, rightHeight) + 1;
}
int main()
{
Node* root = createNode(1);
Node* node2 = createNode(2);
Node* node3 = createNode(3);
Node* node4 = createNode(4);
Node* node5 = createNode(5);
Node* node6 = createNode(6);
Node* node7 = createNode(7);
Node* node8 = createNode(8);
setChild(root, node2, node3);
setChild(node2, node4, node5);
setChild(node3, NULL, node7);
setChild(node5, node6, NULL);
setChild(node4, NULL, node8);
preorderTrav(root);
cout << endl;
inorderTrav(root);
cout << endl;
pastorderTrav(root);
cout << endl;
int height = getTreeHeight(root);
cout << height << endl;
return 0;
}