Binary Tree Preorder Traversal 链表的前序遍历

来源:互联网 发布:查看淘宝关键词排名 编辑:程序博客网 时间:2024/05/02 09:35

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?

/** * 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> ans;    vector<int> preorderTraversal(TreeNode* root) {                if(root!=NULL)        {            ans.push_back(root->val);            preorderTraversal(root->left);            preorderTraversal(root->right);        }        return ans;    }};*/class Solution {public:        vector<int> preorderTraversal(TreeNode* root) {                vector<int> ans;        if(root==NULL)            return ans;        stack<TreeNode *> ss;        ss.push(root);        while(!ss.empty())        {            TreeNode *tmp=ss.top();            ss.pop();            ans.push_back(tmp->val);            if(tmp->right!=NULL)                ss.push(tmp->right);            if(tmp->left!=NULL)                ss.push(tmp->left);                    }        return ans;    }};

0 0
原创粉丝点击