码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Binary Tree Preorder Traversal

时间:2014-12-13 23:12:09      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   on   

实现前序遍历。可参见中序遍历Binary Tree Inorder Traversal

递归:

/**
 * 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 helper144(TreeNode *root, vector<int> &perm)
    {
        if (!root) return;
        perm.push_back(root -> val);
        helper144(root -> left, perm);
        helper144(root -> right, perm);
    }
    vector<int> preorderTraversal(TreeNode *root) 
    {
        vector<int> perm;
        helper144(root, perm);
        return perm;
    }
};

 

非递归:

/**
 * 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> perm;
        stack<TreeNode *> sta;
        TreeNode *p = root;
        
        while(!sta.empty() || p)
        {
            while(p)
            {
                perm.push_back(p->val);
                if (p -> right)
                    sta.push(p -> right);
                p = p -> left;
            }
            if (!sta.empty())
            {
                p = sta.top();
                sta.pop();
            }
        }
        return perm;
    }
};

 

leetcode Binary Tree Preorder Traversal

标签:style   blog   http   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/higerzhang/p/4161904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!