[leetcode] Binary Tree Preorder Traversal 非遞歸先序遍歷

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;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章