[LeetCode] Binary Tree Preorder Traversal, Solution
来源:互联网 发布:jquery.easing.js教程 编辑:程序博客网 时间:2024/06/16 02:21
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?
[Thoughts]
PreOrder:
1. visit node
2. visit node->left
3. visit node->right
对于递归的解法很清晰,
function preorder(root)
if root == NULL return;
print root;
preoder(node->left);
preOrder(node->right);
将该递归函数转换成非递归的话,一般都要借助于栈。
[Code]
1: vector<int> preorderTraversal(TreeNode *root) {
2: stack<TreeNode*> tStack;
3: vector<int> result;
4: while(tStack.size()>0 || root != NULL)
5: {
6: if(root != NULL)
7: {
8: result.push_back(root->val);
9: if(root->right !=NULL)
10: tStack.push(root->right);
11: root = root->left;
12: }
13: else
14: {
15: root = tStack.top();
16: tStack.pop();
17: }
18: }
19: return result;
20: }
Update 08/20/2014. Another way to use stack
1: vector<int> preorderTraversal(TreeNode *root) {
2: stack<TreeNode*> stack;
3: vector<int> result;
4: TreeNode* cur = root;
5: while(cur != NULL || stack.size() != 0)
6: {
7: while(cur != NULL)
8: {
9: result.push_back(cur->val);
10: stack.push(cur);
11: cur = cur->left;
12: }
13: cur = stack.top();
14: stack.pop();
15: cur = cur->right;
16: }
17: return result;
18: }
0 0
- [LeetCode] Binary Tree Preorder Traversal, Solution
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal, Solution
- Binary Tree Preorder Traversal (Recursive solution)
- Lintcode66 Binary Tree Preorder Traversal solution 题解
- 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
- 内联汇编
- Java程序员容易犯的常见十大错误
- rop 文件上传
- [LeetCode] Linked List Cycle II, Solution
- [LeetCode] Reorder List, Solution
- [LeetCode] Binary Tree Preorder Traversal, Solution
- [LeetCode] LRU Cache, Solution
- android方便的自定义Dialog工厂类
- [LeetCode] Max Points on a Line, Solution
- [LeetCode] Sort List, Solution
- [LeetCode] Clone Graph, Solution
- [LeetCode] Evaluate Reverse Polish Notation, Solution
- CodingTMD’s Reading List
- 本博客已搬迁至