【题目描述】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?
非递归法实现二叉树的先序遍历
【解题思路】用迭代法做深度优先搜索的技巧就是使用一个显式声明的Stack存储遍历到节点,替代递归中的进程栈,实际上空间复杂度还是一样的。对于先序遍历,我们pop出栈顶节点,记录它的值,然后将它的左右子节点push入栈,以此类推。
【考察内容】二叉树的先序遍历,栈
/**
* 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) {
stack<TreeNode*> s;
vector<int> res;
if(root!=NULL)
s.push(root);
while(!s.empty()){
TreeNode *curr = s.top();
s.pop();
res.push_back(curr->val);
if(curr->right!=NULL) s.push(curr->right);
if(curr->left!=NULL) s.push(curr->left);
}
return res;
}
};