二叉树
两个值得注意的性质:
1.二叉树是有序树,这个我想了很久不知道为什么,可是为什么二叉树只有三种遍历方式,而不是六种?说明每个形态不同的树都有不同的含义。那完全二叉树和平衡二叉树呢?也是一样的
2.n0=n2+1 推法: n-1=2n2+n1 n=n0+n1+n2
遍历
前 中 后序遍历
#include <iostream>
#include <stdlib.h>using namespace std;typedef struct Node
{struct Node *left;struct Node *right;int data;
} N, Tr;
N *createNode(int data)
{N *a = (N *)malloc(sizeof(N));a->left = a->right = NULL;a->data = data;return a;
}
void pre(Tr *root)
{if (root == NULL)return;cout<< root->data << " ";pre(root->left);pre(root->right);
}
void In(Tr *root)
{if (root == NULL)return;In(root->left);cout << root->data << " ";In(root->right);
}
void aft(Tr *root)
{if (root == NULL)return;aft(root->left);aft(root->right);cout << root->data << " ";
}
int main()
{Tr *root = createNode(3);root->right = createNode(4);root->left = createNode(5);root->left->left = createNode(6);root->left->right = createNode(7);root->right->left = createNode(8);root->right->right = createNode(9);pre(root);cout << endl;In(root);cout << endl;aft(root);cout << endl;
}
栈模拟遍历
void premoni(Tr *root)
{stack<Tr *> number;number.push(root);while (number.size()){Tr *a = number.top();number.pop();cout << a->data << " ";if (a->right != NULL)number.push(a->right);if (a->left != NULL)number.push(a->left);}
}
void Inmoni(Tr *root)
{stack<N *> number;Tr *pnew = root;while (pnew != NULL || number.size()){while (pnew != NULL){number.push(pnew);pnew = pnew->left;}pnew = number.top();number.pop();cout << pnew->data << " ";pnew = pnew->right;}
}
void aftmoni(Tr *root)
{stack<N *> St;stack<int> number;Tr *pnew = root;St.push(root);while (St.size()){pnew = St.top();St.pop();number.push(pnew->data);if (pnew->left != NULL)St.push(pnew->left);if (pnew->right != NULL)St.push(pnew->right);}while (number.size()){cout << number.top() << " ";number.pop();}
}