LeetCode | Binary Tree Preorder Traversal

来源:互联网 发布:zbrush4r7注册机 mac 编辑:程序博客网 时间:2024/06/08 19:46

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

思路:本题为二叉树的先序遍历,有两种方法。1、采用递归的方法  2、添加一个辅助的栈

方法1:递归

#include "stdafx.h"#include <stack>#include <vector>#include <iostream>using namespace std;
//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) {if(root)path(root);return v;}void path(TreeNode* root){if(root){v.push_back(root->val);//输出根结点if(root->left)path(root->left);//遍历左子树if(root->right)path(root->right);//遍历右子树}}private:vector<int> v;};

方法2:辅助栈

栈是先进后出的结构,因此先将右子树压入栈,再压入左子树,那么在栈顶的就是左子树,符合先序遍历的特点,访问完根结点后,总是先访问左子树,再访问右子树。

#include "stdafx.h"#include <stack>#include <vector>using namespace std;
//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) {        TreeNode* t;if(root){s.push(root);//压入根结点while(!s.empty()){t = s.top();v.push_back(t->val);//输出根结点s.pop();if(t->right)s.push(t->right);//压入右子树if(t->left)s.push(t->left);//压入左子树}}return v;    }private:stack<TreeNode*> s;vector<int> v;};





0 0
原创粉丝点击