[LeetCode]Binary Tree Preorder Traversal
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?
思考:不可以递归,那么用栈存储结点。
先用递归法做,算是加深记忆。需要注意ret需要清空,不然会记录上一次测试用例,所以将先序遍历单独写出来。
class Solution { private: vector<int> ret; public: void preorder(TreeNode *root) { if(root) { ret.push_back(root->val); preorder(root->left); preorder(root->right); } } vector<int> preorderTraversal(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ret.clear(); preorder(root); return ret; } };
非递归法:用栈存储遍历过的结点,先右子树后子树。
class Solution { private: vector<int> ret; public: vector<int> preorderTraversal(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ret.clear(); if(!root) return ret; stack<TreeNode *> s; s.push(root); while(!s.empty()) { TreeNode *cur=s.top(); s.pop(); ret.push_back(cur->val); if(cur->right) s.push(cur->right); if(cur->left) s.push(cur->left); } return ret; } };