LeetCode --- Binary Tree Preorder Traversal
来源:互联网 发布:linux获得root权限 编辑:程序博客网 时间:2024/06/03 20:44
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?
先序遍历二叉树。
递归方法:
void PreOrderTraversal(BiTree *root){ if(!root) return; cout<<root->data<<endl; PreOrderTraversal(root->lchild); PreOrderTraversal(root->rchild);}
非递归遍历:
class Solution {public: vector<int> preorderTraversal(TreeNode *root) {vector<int>output;vector<TreeNode*>storage;output.clear();storage.clear();if (root == NULL){return output;}TreeNode* temp = root;while (temp != NULL || storage.size() > 0){while (temp != NULL){output.push_back((*temp).val);storage.push_back(temp);temp = temp->left;}if (storage.size() > 0){TreeNode* top = storage.back();storage.pop_back();temp = top->right;}}return output; }};
相对于后续遍历,先序遍历二叉树要好理解的多。
(1)如果树为空,则直接返回。
(2)将根节点压入到临时存储栈,进入循环。
(3)取栈顶节点,输出该节点值,然后一直循环,将该节点及其左孩子和孩子的左孩子。。。加入到存储栈。
(4)取栈顶节点,出栈,然后将栈顶节点的右孩子赋值给临时节点temp,如果非空,则继续该节点的步骤(3)。如果为空,则会继续取出栈顶元素,出栈。。。。
(5)直到临时存储栈中没有节点位置,出循环,输出结果
0 0
- LeetCode Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- Leetcode Binary Tree Preorder Traversal
- LeetCode:Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- LeetCode:Binary Tree Preorder Traversal
- [LeetCode]Binary Tree Preorder Traversal
- [LeetCode] Binary Tree Preorder Traversal
- LeetCode | Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- [LeetCode] Binary Tree Preorder Traversal
- LeetCode - Binary Tree Preorder Traversal
- LeetCode - Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal
- [LeetCode]Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal - LeetCode
- [Leetcode] Binary Tree Preorder Traversal
- C#中 MouseLeftButtonDown MouseLeftButtonUp MouseMove 使用
- 位排序
- 二天个人提供乳房和天赋规划图
- 最近需要看的几本书
- [资源推荐] 开源工具链博客
- LeetCode --- Binary Tree Preorder Traversal
- UVA - 10603 Fill(bfs+优先队列+动态规划)
- 黑马程序员—(iOS开发)C语言简单编程---(二)
- 二条特让他让他一人一天有图有
- 不重复随机数列生成算法
- 【Java集合源码剖析】LinkedList源码剖析
- 多线程
- 数据结构学习笔记(三)---求1+2+3+...+100的和
- ZOJ 2588 Burning Bridges(判断割边)