标签:stack return 算法 values class end order bin while
模板:
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; } };
标签:stack return 算法 values class end order bin while
原文地址:http://www.cnblogs.com/Atanisi/p/6827023.html