测试地址链接:
前序遍历:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/
后续遍历:http://oj.leetcode.com/problems/binary-tree-postorder-traversal/
最基础的数据结构知识,很多二叉树的操作都是基于遍历来实现的,在递归时一定要注意遍历的顺序。直接贴代码吧
前序:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> v;
Traverse(v, root);
return v;
}
void Traverse(vector<int> &v, TreeNode *p) {
if (p == NULL) return;
v.push_back(p->val);
if (p->left != NULL)
Traverse(v, p->left);
if (p->right != NULL)
Traverse(v, p->right);
}
};
后序
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> returnValue;
Traverse(returnValue, root);
return returnValue;
}
void Traverse(vector<int> &ret, TreeNode *node)
{
if (node == NULL) return;
if (node->left != NULL)
Traverse(ret, node->left);
if (node->right != NULL)
Traverse(ret, node->right);
ret.push_back(node->val);
}
};