[LeetCode] Binary Tree Preorder Traversal 二叉树的先序遍历
2014-12-05 16:29
405 查看
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
一般我们提到树的遍历,最常见的有先序遍历,中序遍历,后序遍历和层序遍历,它们用递归实现起来都非常的简单。而题目的要求是不能使用递归求解,于是只能考虑到用非递归的方法,这就要用到stack来辅助运算。由于先序遍历的顺序是"根-左-右", 算法为:
1. 把根节点push到栈中
2. 循环检测栈是否为空,若不空,则取出栈顶元素,保存其值,然后看其右子节点是否存在,若存在则push到栈中。再看其左子节点,若存在,则push到栈中。
代码如下:
LeetCode All in One 题目讲解汇总(持续更新中...)
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来辅助运算。由于先序遍历的顺序是"根-左-右", 算法为:
1. 把根节点push到栈中
2. 循环检测栈是否为空,若不空,则取出栈顶元素,保存其值,然后看其右子节点是否存在,若存在则push到栈中。再看其左子节点,若存在,则push到栈中。
代码如下:
/** * 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> res; stack<TreeNode*> s; if (!root) return res; s.push(root); while (!s.empty()) { TreeNode *p = s.top(); res.push_back(p->val); s.pop(); if (p->right) s.push(p->right); if (p->left) s.push(p->left); } return res; } };
LeetCode All in One 题目讲解汇总(持续更新中...)
相关文章推荐
- LeetCode Binary Tree Preorder Traversal (二叉树先序遍历非递归)
- Leetcode Binary Tree Preorder Traversal 二叉树先序遍历
- LeetCode 144 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-Construct Binary Tree from Preorder and Inorder Traversal-前序中序恢复二叉树-递归
- [LeetCode]108. Construct Binary Tree from Preorder and Inorder Traversal由前序序列和中序序列重建二叉树
- 【LeetCode】Binary Tree Preorder Traversal 二叉树的前序遍历(3种方法)- Easy+
- [leetcode]Construct Binary Tree from Preorder and Inorder Traversal(根据前序、中序遍历确定一棵二叉树 C语言)
- [LeetCode] Binary Tree Preorder Traversal (非递归的先序遍历)
- leetcode:二叉树之Binary Tree Preorder Traversal
- [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树
- 【二叉树先序遍历】Binary Tree Preorder Traversal
- leetcode:二叉树之Construct Binary Tree from Preorder and Inorder Traversal
- 【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal(构造二叉树)】
- 【LeetCode笔记】Construct Binary Tree from Preorder and Inorder Traversal 前序、中序还原二叉树
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal (用先序和中序树遍历来建立二叉树)
- leetcode--第5章--树-5.1二叉树的遍历--5.1.1 binary tree preorder traversal