首页 > 代码库 > [LeetCode]Binary Tree Preorder Traversal
[LeetCode]Binary Tree Preorder Traversal
【题目】
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?
【代码一】
/********************************* * 日期:2014-10-15 * 作者:SJF0115 * 题号: Binary Tree Preorder Traversal * 来源:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/ * 结果:AC * 来源:LeetCode * 总结: **********************************/ #include <iostream> #include <malloc.h> #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: vector<int> v; void PreOrder(TreeNode *root){ if (root == NULL){ return; } v.push_back(root->val); PreOrder(root->left); PreOrder(root->right); } vector<int> preorderTraversal(TreeNode *root) { PreOrder(root); return v; } }; //按先序序列创建二叉树 int CreateBTree(TreeNode* &T){ char data; //按先序次序输入二叉树中结点的值(一个字符),‘#’表示空树 cin>>data; if(data =http://www.mamicode.com/= '#'){>【代码二】
非递归实现
class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> v; stack<TreeNode*> s; TreeNode* p = root; //栈不空或者p不空时循环 while(p != NULL || !s.empty()){ if(p != NULL){ //访问根节点 v.push_back(p->val); //根节点插入栈中,用来访问右子树 s.push(p); //遍历左子树 p = p->left; } else{ //左子树访问完毕,访问右子树 p = s.top(); s.pop(); p = p->right; } } return v; } };
[LeetCode]Binary Tree Preorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。