Leetcode 144

来源:互联网 发布:推荐算法源代码 编辑:程序博客网 时间:2024/05/06 16:51

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].

/** * 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> a;        stack<TreeNode*> s;        int i = 0;        TreeNode* p = root;                while(true)        {            while(p)            {                a.insert(a.begin()+i,p->val);                i++;                s.push(p->right);                p = p->left;            }                        if(s.empty()) break;                        p = s.top();            s.pop();        }        return a;    }};


0 0
原创粉丝点击