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

144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)

时间:2016-03-19 18:10:54      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

翻译

给定一个二叉树,返回其前序遍历的节点的值。

例如:
给定二叉树为 {1#, 2, 3}
   1
         2
    /
   3
返回 [1, 2, 3]

备注:用递归是微不足道的,你可以用迭代来完成它吗?

原文

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?

分析

题目让咱试试迭代呢,不过还是先老老实实把递归给写出来再说吧~

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> v;

    vector<int> preorderTraversal(TreeNode* root) {
        if (root != NULL) {
            v.push_back(root->val);
            preorderTraversal(root->left);
            preorderTraversal(root->right);
        }
        return v;
    }
};

紧接着,咱来写迭代的……

/**
* Definition for a binary tree node.
* 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;
        stack<TreeNode*> tempStack;
        while (!tempStack.empty() || root != NULL) {
            if (root != NULL) {
                result.push_back(root->val);
                tempStack.push(root);
                root = root->left;
            }
            else {
                root = tempStack.top();
                tempStack.pop();
                root = root->right;
            }
        }
        return result;
    }
};

144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)

标签:

原文地址:http://blog.csdn.net/nomasp/article/details/50931535

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