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

Binary Tree Preorder Traversal -- LeetCode

时间:2016-01-29 08:46:37      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

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].

思路:递归和迭代。

//递归
class Solution {
public:
    void help(vector<int>& res, TreeNode* root)
    {
        if (!root) return;
        res.push_back(root->val);
        help(res, root->left);
        help(res, root->right);
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        help(res, root);
        return res;
    }
};

  

//迭代
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        stack<TreeNode *> sta;
        sta.push(root);
        while (!sta.empty())
        {
            TreeNode* cur = sta.top();
            sta.pop();
            res.push_back(cur->val);
            if (cur->right) sta.push(cur->right);
            if (cur->left) sta.push(cur->left);
        }
        return res;
    }
};

  

Binary Tree Preorder Traversal -- LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5167937.html

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