Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [1,2,3]
.
c++版:
/**
* 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> result;
vector<int> left;
vector<int> right; if(root == NULL) return result;
result.push_back(root->val);
left = preorderTraversal(root->left);
right = preorderTraversal(root->right); if(left.size() != )
result.insert(result.end(), left.begin(), left.end());
if(right.size() != )
result.insert(result.end(), right.begin(), right.end()); return result; }
};
Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [3,2,1]
.
C++版本:
/**
* 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) {
vector<int> ret;
dfs(root, ret);
return ret;
} void dfs(TreeNode* root, vector<int>& ret)
{
if(NULL == root)
return ;
dfs(root->left, ret);
dfs(root->right, ret);
ret.push_back(root->val);
} };