解题思路:
前序遍历。
一,递归法(超简单):
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> ret;
vector<int> preorderTraversal(TreeNode* root) {
ret.clear();
DFS(root);
return ret;
}
void DFS(TreeNode* root){
if (root == NULL) return ;
ret.push_back(root->val);
DFS(root->left);
DFS(root->right);
}
};
迭代法:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty()){
TreeNode* node = sta.top();
sta.pop();
if (node == NULL) continue;
ret.push_back(node->val);
sta.push(node->right);
sta.push(node->left);
}
return ret;
}
};