leetcode之Binary Tree Preorder Traversal

来源:互联网 发布:群晖端口转发设置 编辑:程序博客网 时间:2024/05/02 20:23

问题描述如下:

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?

问题链接

cpp代码如下:

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


0 0