给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归解法:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector<int> fNum; public: vector<int> preorderTraversal(TreeNode* root) { init(); fDfs(root); return fNum; } void fDfs(TreeNode* root) { if (root!= NULL) { fNum.push_back(root->val); fDfs(root->left); //遍历左子树 fDfs(root->right); //遍历右子树 } } void init() { fNum.clear(); } };
迭代算法:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector<int> num; stack<TreeNode* > fNum; public: vector<int> preorderTraversal(TreeNode* root) { init(); bfs(root); return num; } void bfs(TreeNode* root) { while (root!= NULL|| ! fNum.empty()) { while (root!= NULL) { fNum.push(root); num.push_back(root->val); root = root->left; } root = fNum.top(); fNum.pop(); root = root->right; } } void init() { num.clear(); if(! fNum.empty()) fNum.pop(); } };