leetcode 题解:Binary Tree Preorder Traversal (二叉树的先序遍历)
2014-06-25 21:23
459 查看
题目:
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?
说明:
1)递归和非递归实现,其中非递归有两种方法
2)复杂度,时间O(n),空间O(n)
实现:
一、递归
View Code
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?
说明:
1)递归和非递归实现,其中非递归有两种方法
2)复杂度,时间O(n),空间O(n)
实现:
一、递归
/** * 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) { stack<TreeNode *> preorder_stack; TreeNode *p=NULL; vector<int> preorder_vec; if(root==NULL) return preorder_vec;//若为空树,则返回空vector preorder_stack.push(root);//当前节点入栈 while(!preorder_stack.empty()) { p=preorder_stack.top();//栈顶节点出栈、输出 preorder_stack.pop(); preorder_vec.push_back(p->val); //注意,下面入栈顺序不能错 ,因为先右后左, //这样出栈时先遍历才是左孩子(左->中->右) if(p->right) preorder_stack.push(p->right);//若存在右孩子,则入栈 if(p->left) preorder_stack.push(p->left);//若存在左孩子,则入栈 } return preorder_vec; } };
View Code
相关文章推荐
- [LeetCode] Binary Tree Preorder Traversal 二叉树的先序遍历
- Leetcode Binary Tree Preorder Traversal 二叉树先序遍历
- LeetCode:Binary Tree Preorder Traversal(二叉树的先序遍历)
- 【leetcode】非递归先序遍历二叉树(Binary Tree Preorder Traversal)
- LeetCode 144 Binary Tree Preorder Traversal (先序遍历二叉树)
- LeetCode Binary Tree Preorder Traversal (二叉树先序遍历非递归)
- leetcode题解:Binary Tree Postorder Traversal (二叉树的后序遍历)
- [LeetCode]题解(python):144-Binary Tree Preorder Traversal
- Leetcode Construct Binary Tree from Preorder and Inorder Traversal 前序中序遍历重组二叉树
- 【leetcode 先序遍历】Binary Tree Preorder Traversal
- 【LeetCode-面试算法经典-Java实现】【144-Binary Tree Preorder Traversal(二叉树非递归前序遍历)】
- leetcode--第5章--树-5.1二叉树的遍历--5.1.1 binary tree preorder traversal
- LeetCode(Construct Binary Tree from Preorder and Inorder Traversal )根据二叉树的中序遍历和后序遍历重建二叉树
- LeetCode-Construct Binary Tree from Preorder and Inorder Traversal-前序中序恢复二叉树-递归
- leetcode:二叉树之Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal 二叉树的先序@LeetCode
- 144 Binary Tree Preorder Traversal(二叉树先序遍历Medium)
- 【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal(构造二叉树)】
- [LeetCode]题解(python):105-Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 题解:Binary Tree Level Order Traversal (二叉树的层序遍历)