首页 > 其他 > 详细

leetcode笔记:Binary Tree Preorder Traversal

时间:2015-10-14 00:25:29      阅读:241      评论: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].

Note: Recursive solution is trivial, could you do it iteratively?

二. 题目分析

可使用递归解法,而只要是能用递归,也就是说能用栈来还原递归过程,因此方法不止一种。

使用栈来实现二叉树的遍历:首先在stack中压入当前的root,由于是前序遍历,故树是按照先根,然后左子树和后右子树进行访问,故pop取出一个结点,将它的value加入访问序列。之后压入它的右子树和左子树。直到stack为空。

三. 示例代码

递归解法:

#include <iostream>
#include <vector>

using namespace std;

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

class Solution
{
public:
    void preorder(TreeNode *root, vector<int> &k)
    {
        if (root != NULL)
        {
        k.push_back(root->val);
        preorder(root->left, k);
        preorder(root->right, k);
        }
    }

    vector<int> preorderTraversal(TreeNode *root)
    {
        vector<int> temp;
        preorder(root, temp);
        return temp;
    }
};

非递归解法(stack实现):

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

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> temp;
        temp.clear();
        stack<TreeNode *> k;
        if (root == NULL)
            return temp;
        k.push(root);
        while (!k.empty())
        {
            TreeNode *node = k.top();
            k.pop();
            temp.push_back(node->val);
            if (node->right != NULL)
                k.push(node->right);
            if (node->left != NULL)
                k.push(node->left);
        }
        return temp;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode笔记:Binary Tree Preorder Traversal

原文:http://blog.csdn.net/liyuefeilong/article/details/49106889

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!