标签:
给定一个二叉树,返回其前序遍历的节点的值。
例如:
给定二叉树为 {1,#, 2, 3}
1
2
/
3
返回 [1, 2, 3]
备注:用递归是微不足道的,你可以用迭代来完成它吗?
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].
Note: Recursive solution is trivial, could you do it iteratively?
题目让咱试试迭代呢,不过还是先老老实实把递归给写出来再说吧~
/**
* 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> v;
vector<int> preorderTraversal(TreeNode* root) {
if (root != NULL) {
v.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return v;
}
};
紧接着,咱来写迭代的……
/**
* 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> preorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode*> tempStack;
while (!tempStack.empty() || root != NULL) {
if (root != NULL) {
result.push_back(root->val);
tempStack.push(root);
root = root->left;
}
else {
root = tempStack.top();
tempStack.pop();
root = root->right;
}
}
return result;
}
};
144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)
标签:
原文地址:http://blog.csdn.net/nomasp/article/details/50931535