Binary Tree Preorder Traversal

来源:互联网 发布:ios远程访问mac 编辑:程序博客网 时间:2024/06/04 18:26

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?

前序遍历,同样不能使用递归

class Solution {public:    vector<int> preorderTraversal(TreeNode *root) {        vector<int> rel;        if(root==NULL) return rel;        if(root) s.push(root);        while(!s.empty()){            TreeNode * p = s.top();            s.pop();            while(p!=NULL){                rel.push_back(p->val);                if(p->right!=NULL) s.push(p->right);                p = p->left;            }        }        return rel;    }    stack<TreeNode*> s;};


0 0