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?

分析:这道题与之前那道中序遍历是一样的题型,借助栈stack数据结构。先在stack中push进root,由于是前序遍历,故根结点的访问先于左结点和右结点,因此pop出一个结点,将它的值存入序列中,然后将它的右结点压入栈中,在压入它的左结点(这里为什么要先压入右结点呢?因为左结点要先于右结点访问,但是由于栈是后进先出,故要把左结点后于右结点压入栈中),直至栈为空位置。

/**
 * 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) {
        stack<TreeNode*> StackTree;
        vector<int> data;
        if(root==NULL)
            return data;
        StackTree.push(root);
        while(!StackTree.empty())
        {
            TreeNode *CurrentNode=StackTree.top();
            StackTree.pop();
            data.push_back(CurrentNode->val);
            if(CurrentNode->right!=NULL)
                StackTree.push(CurrentNode->right);
            if(CurrentNode->left!=NULL)
                StackTree.push(CurrentNode->left);
        }
        return data;
    }
};

 递归方法:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void Traversal(TreeNode *root,vector<int> &data)
    {
        if(root==NULL)
            return;
        data.push_back(root->val);
        Traversal(root->left,data);
        Traversal(root->right,data);
    }
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> data;
        Traversal(root,data);
        return data;
    }
};

 

 

 

posted @ 2014-03-07 21:25  Awy  阅读(262)  评论(0编辑  收藏  举报