题解 | # 实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
递归实现先序遍历,中序遍历,后序遍历
先序遍历:根节点->左孩子->右孩子;
中序遍历:左孩子->根节点->右孩子;
后序遍历:左孩子->右孩子->根节点;
/**
- struct TreeNode {
- int val;
- struct TreeNode *left;
- struct TreeNode *right;
- };
- /
class Solution {
public:
/*
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
vector<int> pre;
vector<int> inr;
vector<int> pos;
//先序遍历
void preRecure(TreeNode</int></int></int> root)
{
if(root == NULL) return;
pre.push_back(root->val);
preRecure(root->left);
preRecure(root->right);
}
//中序遍历
void inrRecure(TreeNode* root)
{
if(root == NULL) return;
inrRecure(root->left);
inr.push_back(root->val);
inrRecure(root->right);
}
//后序遍历
void posRecure(TreeNode* root)
{
if(root == NULL) return;
posRecure(root->left);
posRecure(root->right);
pos.push_back(root->val);
}
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
vector<vector<int>> res;
if(root == NULL) return res;
preRecure(root);
inrRecure(root);
posRecure(root);
res.push_back(pre);
res.push_back(inr);
res.push_back(pos);
return res;
}
};</int></int>