Binary Tree Preorder Traversal--LeetCode
2017-10-15 16:09
204 查看
1.题目
Binary Tree Preorder TraversalGiven 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?
2.题意
二叉树前序遍历3.分析
1)递归是最简单的方法直接按照root、左、右的顺序放进vector即可
算法的时间复杂度是O(n),而空间复杂度则是递归栈的大小,即O(logn)
2)借助栈来模拟递归
先将root结点进栈,然后按层序遍历
利用栈后进先出的特点,先让右孩子节点进栈,再让左孩子节点进栈
在每一个非空的下一层依次取出左右孩子节点
算法时间复杂度是O(n),空间复杂度是栈的大小O(logn)
4.代码
1) 递归版class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> result; preorder(result, root); return result; } private: void preorder(vector<int> &result, TreeNode *root) { if(root == nullptr) return; result.push_back(root->val); preorder(result, root->left); preorder(result, root->right); } };
2) 迭代版
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> result; if(root == nullptr) return result; stack<const TreeNode*> s; if(root != nullptr) s.push(root); while(!s.empty()) { const TreeNode *p = s.top(); s.pop(); result.push_back(p->val); if(p->right != nullptr) s.push(p->right); if(p->left != nullptr) s.push(p->left); } return result; } };
相关文章推荐
- Binary Tree Preorder Traversal 二叉树的先序@LeetCode
- [leetcode-105]Construct Binary Tree from Preorder and Inorder Traversal(java)
- △【LeetCode】Binary Tree Preorder Traversal
- leetCode(18):Construct Binary Tree from Preorder and Inorder (Inorder and Postorder) Traversal
- leetcode: Binary Tree Preorder Traversal
- LeetCode : Binary Tree Preorder Traversal
- 【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal【java】
- leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 中前序构造BST
- LeetCode – Refresh – Construct Binary Tree from Inorder and Preorder Traversal
- [LeetCode]题解(python):144-Binary Tree Preorder Traversal
- leetcode_144_Binary Tree Preorder Traversal
- LeetCode:Construct Binary Tree from Inorder and Postorder Traversal,Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Array——Construct Binary Tree from Preorder and Inorder Traversal(105)
- LeetCode Binary Tree Preorder Traversal
- LeetCode之Construct Binary Tree from Preorder and Inorder Traversal
- leetcode144 Binary Tree Preorder Traversal
- leetcode - Binary Tree Preorder Traversal
- [leetcode][tree] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal