Binary Tree Preorder Traversal
来源:互联网 发布:藤原文太 知乎 编辑:程序博客网 时间:2024/05/17 03:37
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?
Tree Stack
分别用递归和栈来解决。
递归:
vector<int> result; void preorder(TreeNode* p){ if (p == NULL) return; result.push_back(p->val); preorder(p->left); preorder(p->right); } vector<int> preorderTraversal(TreeNode* root) { preorder(root); return result;//隔开,才能返回 }
栈:(空间复杂度O(n))
vector<int> preorderTraversal(TreeNode* root) { vector<int> arr; stack<TreeNode*> s; TreeNode* p; if (root == NULL) return arr; s.push(root); while (!s.empty()){ p = s.top(); arr.push_back(p->val); s.pop(); if (p->right) s.push(p->right); if (p->left) s.push(p->left); } return arr;}
0 0
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- 如何开机不桌面进入直接运行某一个程序
- 线程与进程
- 最好不要在C++动态库与调用着之间传递STL模版
- 谈谈Android中的SurfaceTexture
- Logstash pattern 例子
- Binary Tree Preorder Traversal
- MD5加密字符
- MySQL UUID函数的详解
- linux c选择排序
- knockout示例
- 找新朋友(1286)
- maven3下载源码
- yate学习--yatesip.h--class YSIP_API SIPParty : public RefObjec
- 总结初次使用SQLite的错误点