leetcode #144 in cpp

来源:互联网 发布:lol有没有mac版本 编辑:程序博客网 时间:2024/05/09 14:45

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?

Code:

/** * 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> res;         stack<TreeNode*> stk;         if(root) stk.push(root);        TreeNode*cur;         while(!stk.empty()){            cur = stk.top();            stk.pop();            res.push_back(cur->val);            if(cur->right) stk.push(cur->right);            if(cur->left) stk.push(cur->left);        }        return res;             }};


0 0
原创粉丝点击