Leetcode 144 (three methods)
I learned tree data structure again and watched the video by IIT professor.
Leetcode 144 solved by recursion is very simple to understand, but i try used
other way to conquer it.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
Method one : RECURSION
class Solution {
public:
void Traversal(TreeNode* cur, vector<int>& re) {
if (cur == NULL) return;
re.push_back(cur -> val);
Traversal(cur -> left, re);
Traversal(cur -> right, re);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
Traversal(root,ret);
return ret;
}
};
Method two : BFS
class Solution {
public:
void bfs(TreeNode* cur, queue<int>& q, vector<int>& r) {
if (!cur) return ;
q.push(cur -> val);
bfs(cur->left,q,r);
bfs(cur->right,q,r);
r.push_back(q.front());
q.pop();
}
vector<int> preorderTraversal(TreeNode* root) {
queue<int> q;
vector<int> ret;
bfs(root, q, ret);
return ret;
}
};
Method three : STACK
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
vector<int> ret;
if (root) stk.push(root);
while (!stk.empty()) {
TreeNode *node = stk.top();
ret.push_back(node -> val);
stk.pop();
if (node -> right) stk.push(node -> right);
if (node -> left) stk.push(node -> left);
}
return ret;
}
};
KEEP GOING!
让思维见见世面
浙公网安备 33010602011771号