[leetcode] Binary Tree Preorder Traversal 非递归先序遍历

来源:互联网 发布:店宝宝实物软件 编辑:程序博客网 时间:2024/05/21 14:06

Binary Tree Preorder Traversal

 Total Accepted: 20397 Total Submissions: 58308My Submissions

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?

Have you been asked this question in an interview? 


/** * Definition for binary tree * 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> result;        if(root==NULL) return result;    stack<TreeNode *> mstack;//堆栈模拟递归        mstack.push(root);    while(!mstack.empty())    {        TreeNode * top = mstack.top();        if(mstack.top()!=NULL)        {            result.push_back(mstack.top()->val);            mstack.pop();        }               //注意,先右边,仔细体会        if(top->right!=NULL)    {    mstack.push(top->right);    }    if(top->left!=NULL)    {    mstack.push(top->left);    }        }    return result;    }};


0 0
原创粉丝点击