数据结构学过树的遍历吧,有先序遍历,中序遍历,后序遍历,就是父亲节点应该放哪个位置, 父节点放最前面就是先序遍历,以此类推。
我这题用的迭代的方式,当然很简单。
先序遍历
指先访问根,然后访问孩子的遍历方式,其C代码如下:
void XXBL(tree* root){
//Do Something with root
if(root->lchild!=NULL)
XXBL(root->lchild);
if(root->rchild!=NULL)
XXBL(root->rchild);
}
中序遍历
指先访问左(右)孩子,然后访问根,最后访问右(左)孩子的遍历方式,其C代码如下
void ZXBL(tree* root){
if(root->lchild!=NULL)
ZXBL(root->lchild);
//Do Something with root
if(root->rchild!=NULL)
ZXBL(root->rchild);
}
后序遍历
指先访问孩子,然后访问根的遍历方式,其C代码如下
void HXBL(tree* root){
if(root->lchild!=NULL)
HXBL(root->lchild);
if(root->rchild!=NULL)
HXBL(root->rchild);
//Do Something with root
}
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void postOrder(TreeNode *root,vector<int> &posterTree){
if(root!=NULL){
postOrder(root->left,posterTree);
postOrder(root->right,posterTree);
posterTree.push_back(root->val);
}
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> posterTree;
postOrder(root,posterTree);
return posterTree;
}
};