模板:
1.先序遍历三种方法
1)迭代:
class Solution { public: /** * @param root: The root of binary tree. * @return: Preorder in vector which contains node values. */ vector<int> preorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode*> stack; if (root == NULL) { return res; } stack.push(root); while (!stack.empty()) { TreeNode *node = stack.top(); stack.pop(); res.push_back(node->val); if (node->right != NULL) { stack.push(node->right); } if (node->left != NULL) { stack.push(node->left); } } return res; } };
2)递归:
class Solution { public: void traversal(TreeNode *root, vector<int>& res) { if (root == NULL) { return; } res.push_back(root->val); traversal(root->left, res); traversal(root->right, res); } vector<int> preorderTraversal(TreeNode *root) { vector<int> res; traversal(root, res); return res; } };
3)分治:
class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> res; if (root == NULL) { return res; } vector<int> left = preorderTraversal(root->left); vector<int> right = preorderTraversal(root->right); res.push_back(root->val); res.insert(res.end(), left.begin(), left.end()); res.insert(res.end(), right.begin(), right.end()); return res; } };
模板2:DFS:
1) Traverse
class Solution { public: void traverse(TreeNode *root) { if (root == NULL) { return; } // do something with root traverse(root->left); // do something with root traverse(root->right); // do something with root } };
2) Divide and Conquer
class Solution { public: ResultType traversal(TreeNode * root) { if (root == NULL) { // do something and return } // Divide ResultType left = traversal(root->left); ResultType right = traversal(root->right); // Conquer ResultType result = Merge from left and right return result; } };
栈实现非递归DFS
//preOrderTraversal void preOrderTraversal1(TreeNode* root) { if (root == NULL) { return; } stack<TreeNode*> s; TreeNode* p = root; while (!s.empty() || p) { while (p) { func(p); s.push(p); p = p->left; } if (!s.empty()) { p = s.top(); s.pop(); p = p->right; } } }
void preOrderTraversal2(TreeNode* root) { if (root == NULL) { return; } stack<TreeNode*> s; s.push(root); while (!s.empty()) { TreeNode* tmp = s.top(); s.pop(); func(tmp); if (tmp->right) { s.push(tmp->right); } if (tmp->left) { s.push(tmp->left); } } }
void preOrderTraversal3(TreeNode* root) { if (root == NULL) { return; } stack<TreeNode*> s; s.push(root); TreeNode* tmp = root; while (!s.empty()) { func(tmp); if (tmp->right) { s.push(tmp->right); } if (tmp->left) { s.push(tmp->left); } else { p = s.top(); s.pop(); } } }
//inOrderTraversal void inOrderTraversal1(TreeNode* root) { if (root == NULL) { return; } stack<TreeNode*> s; TreeNode* p = root; while (!s.empty() || p) { while (p) { s.push(p); p = p->left; } if (!s.empty()) { p = s.top(); s.pop(); func(p); p = p->right; } } } //postOrderTraversal