LeetCode:Binary Tree Preorder Traversal

来源:互联网 发布:光纤网络监控安装图解 编辑:程序博客网 时间:2024/06/14 22:54

Binary Tree Preorder Traversal

Total Accepted: 96837 Total Submissions: 256194 Difficulty: Medium

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


0 0