LeetCode:Binary Tree Preorder Traversal(非递归方法前序遍历二叉树)
2015-02-03 10:42
435 查看
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?
使用迭代(非递归)的方法遍历二叉树。
可以使用stack或者list记录遍历的回退路径,实现前序遍历。
两者的时间复杂度均是O(n),额外的stack或者list的空间复杂度都是O(logn),但list内部需要维护结点之间的链接指针,所以stack的实际运行效率要更好一些。
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或者list记录遍历的回退路径,实现前序遍历。
class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> vec; if(root==NULL) return vec; stack<TreeNode*> s; s.push(root); TreeNode *current; while(!s.empty()){ current = s.top(); s.pop(); if(current){ vec.push_back(current->val); s.push(current->right); s.push(current->left); } } return vec; } };
class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> vec; if(root==NULL) return vec; list<TreeNode*> L; L.push_back(root); TreeNode *current; while(!L.empty()){ current = L.front(); L.pop_front(); if(current){ vec.push_back(current->val); L.push_front(current->right); L.push_front(current->left); } } return vec; } };
两者的时间复杂度均是O(n),额外的stack或者list的空间复杂度都是O(logn),但list内部需要维护结点之间的链接指针,所以stack的实际运行效率要更好一些。
相关文章推荐
- LeetCode Binary Tree Preorder Traversal 前序遍历二叉树 递归和非递归解法
- LeetCode:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium
- LeetCode:144_Binary Tree Preorder Traversal | 二叉树的前序遍历 | Medium
- 【leetcode】非递归先序遍历二叉树(Binary Tree Preorder Traversal)
- 【LeetCode 144_二叉树_遍历】Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal 二叉树的前序遍历
- LeetCode Binary Tree Postorder Traversal(二叉树的后序遍历 非递归实现)
- 【LeetCode】Binary Tree Preorder Traversal 二叉树的前序遍历(3种方法)- Easy+
- [Leetcode]Binary Tree Inorder Traversal@python(附前、中、后三种遍历的递归和非递归方法!)
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal (用先序和中序树遍历来建立二叉树)
- leetcode--第5章--树-5.1二叉树的遍历--5.1.1 binary tree preorder traversal
- 【遍历二叉树】01二叉树的前序遍历【Binary Tree Preorder Traversal】
- lintcode 容易题:Binary Tree Preorder Traversal 二叉树的前序遍历
- LeetCode-Construct Binary Tree from Preorder and Inorder Traversal-前序中序恢复二叉树-递归
- leetcode_144题——Binary Tree Preorder Traversal(二叉树,递归,栈的使用)
- LeetCode-105:Construct Binary Tree from Preorder and Inorder Traversal (利用先序和中序遍历构建二叉树) -- medium
- LeetCode(Construct Binary Tree from Preorder and Inorder Traversal )根据二叉树的中序遍历和后序遍历重建二叉树
- [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树
- LeetCode OJ:Binary Tree Preorder Traversal(前序遍历二叉树)
- LeetCode | Binary Tree Level Order Traversal II(二叉树层序遍历II)