[LeetCode]Binary Tree Preorder Traversal
来源:互联网 发布:百雀羚网络推广策划案 编辑:程序博客网 时间:2024/05/18 06:23
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?
二叉树的前序遍历。题目要求用循环来做,用根节点root遍历这个树,用一个栈存储stk当前二叉树结点。当root为NULL时和stk为空同时成立时结束循环(如果只在root为空时结束循环,只有右子树时会在遍历右子树前直接结束循环)。其中循环过程如下:
(1)如果root不为空:
将root的值放入path中->root入栈->root指向其左孩子结点;(此时stk栈顶为root的父亲结点)
(2)如果root为空,且stk不为空:返回root父亲节点,root指向兄弟结点。
root指向右孩子结点->stk出栈;(父亲几点的两个孩子结点已经遍历完成,stk此时栈顶为root祖父结点)
最后返回path。代码如下所示:
/** * 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) { vector<int> path; stack<TreeNode*> stk; while(root != NULL || !stk.empty()) { if(root != NULL) { while(root) { path.push_back(root->val); stk.push(root); root=root->left; } } else{ root = stk.top()->right; stk.pop(); } } return path; }};参考代码:
http://blog.csdn.net/doc_sgl/article/details/14436785
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
- HDU 2003 求绝对值
- GCC 编译器寄存器分配各阶段主要任务
- GreenDao官方文档翻译上 下
- HDU 2105 The Center of Gravity
- HDU 2004 成绩转换
- [LeetCode]Binary Tree Preorder Traversal
- vmware安装linux的vmware tools 并共享windows下文件夹的
- 博客开篇
- Android.mk各种文件编译汇总
- poj 3264 Balanced Lineup
- Android 自定义 ViewPager 打造千变万化的图片切换效果
- HDU 2005 第几天?
- SQL语句大全
- bat 以管理员权限运行但目录不是打开目录的解决办法。