节点结构:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
前序遍历:
//递归遍历
void PreScan(TreeNode* T)
{
if(!T)
return;
cout << T->val << endl;
PreScan(T->left);
PreScan(T->right);
}
中序遍历:
void PreScan(TreeNode* T)
{
if(!T)
return;
PreScan(T->left);
cout << T->val << endl;
PreScan(T->right);
}
后序遍历:
void PreScan(TreeNode* T)
{
if(!T)
return;
PreScan(T->left);
PreScan(T->right);
cout << T->val << endl;
}
层序遍历:
利用先进先出的原则,使用队列,对每一层的 节点进行遍历
//层序遍历
void LayerScan(TreeNode* T)
{
if(!T)
return;
//定义一个队列
queue<TreeNode*> rel;
rel.push(T);
while(!rel.empty())
{
TreeNode* Front = rel.front();
cout << Front->val << endl;
rel.pop();
if(Front->left)
rel->push(Front->left);
if(Front->right)
rel->push(Front->right);
}
}