LeetCode Binary Tree Preorder Traversal
來源:程序員人生 發布時間:2015-04-01 08:17:23 閱讀次數:2520次
1.題目
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?
2.解決方案1
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> ans;
deque<TreeNode*> node_list;
if(root == NULL) return ans;
node_list.push_front(root);
while(!node_list.empty())
{
TreeNode *cur = node_list.back();
node_list.pop_back();
ans.push_back(cur -> val);
if(cur -> right != NULL) node_list.push_back(cur -> right);
if(cur -> left != NULL) node_list.push_back(cur -> left);
}
return ans;
}
};
思路:先序遍歷的非遞歸方式還比較容易寫,就是廣度優先或呼吸遍歷。要1個隊列來支持。
3.解決方案2
class Solution {
public:
vector<int> path;
void preorder(TreeNode *root){
if(!root)
return;
path.push_back(root->val);
//if(root->left)
preorder(root->left);
//if(root->right)
preorder(root->right);
}
vector<int> preorderTraversal(TreeNode *root) {
preorder(root);
return path;
}
};
思路:遞歸就是簡單,但是速度很慢。http://www.waitingfy.com/archives/1594
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈