LeetCode144:Binary Tree Preorder Traversal

mickole發表於2014-02-17

題目:

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?

解題思路:

利用棧實現,很簡單的一題,不多說了,直接上程式碼

實現程式碼:

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

/**
Given a binary tree, return the preorder  traversal of its nodes' values.
*/
 

struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;    
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

void addNode(TreeNode* &root, int val)
{
    if(root == NULL)
    {
        TreeNode *node = new TreeNode(val);
        root = node;
    }
    else if(root->val < val)
    {
        addNode(root->right, val);
    }
    else if(root->val > val)
    {
        addNode(root->left, val);
    }
}

void printTree(TreeNode *root)
{
    if(root)
    {
        cout<<root->val<<" ";
        printTree(root->left);
        printTree(root->right);
    }
}

class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> ivec;
        if(root)
        {    
            stack<TreeNode *> tstack;
            TreeNode *p = root;            
            while(p || !tstack.empty())
            {
                while(p)
                {
                    ivec.push_back(p->val);
                    tstack.push(p);
                    p = p->left;
                }
                if(!tstack.empty())
                {
                    TreeNode *t = tstack.top();
                    tstack.pop();
                    p = t->right;
                }
            }
            
        }
        return ivec;
                       
    }
};
int main(void)
{
    TreeNode *root = new TreeNode(5);
    addNode(root, 7);
    addNode(root, 3);
    addNode(root, 15);
    addNode(root, 1);
    printTree(root);
    cout<<endl;
    
    Solution solution;
    vector<int> v = solution.preorderTraversal(root);
    vector<int>::iterator iter;
    for(iter = v.begin(); iter != v.end(); ++iter)
        cout<<*iter<<" ";
    cout<<endl;
    
    return 0;
}

相關文章