leetcode之Binary Tree Preorder Traversal

问题描述如下:

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;
    }
};


猜你喜欢

转载自blog.csdn.net/wocaoqwerty/article/details/41773715