标签:des style blog color io os ar for sp
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() != 0) result.insert(result.end(), left.begin(), left.end()); if(right.size() != 0) result.insert(result.end(), right.begin(), right.end()); return result; } };
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); } };
Binary Tree Preorder Traversal and Binary Tree Postorder Traversal
标签:des style blog color io os ar for sp
原文地址:http://www.cnblogs.com/zlz-ling/p/4035509.html