https://leetcode.com/problems/binary-tree-paths/description/
Solution 1. Iterative traversal.
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(!root) return res;
stack<TreeNode*> st;
stack<string> stp;
st.push(root);
stp.push(to_string(root->val));
TreeNode* node;
while(!st.empty()){
node = st.top();
st.pop();
string path = stp.top();
stp.pop();
if(!node->left && !node->right) {
res.push_back(path);
}
if(node->right){
st.push(node->right);
stp.push(path + "->" + to_string(node->right->val));
}
if(node->left) {
st.push(node->left);
stp.push(path + "->" + to_string(node->left->val));
}
}
return res;
}
Solution 2. Recursive traversal.
void preOrder(TreeNode* node, vector<string>& res, string s) {
if(!node->left && !node->right) {
res.push_back(s);
return;
}
if(node->left) preOrder(node->left, res, s + "->" + to_string(node->left->val));
if(node->right) preOrder(node->right, res, s + "->" + to_string(node->right->val));
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(!root) return res;
preOrder(root, res, to_string(root->val));
return res;
}
or,
void preOrder(TreeNode* node, vector<string>& res, string s) {
s += "->" + to_string(node->val);
if(!node->left && !node->right) res.push_back(s.substr(2));
if(node->left) preOrder(node->left, res, s);
if(node->right) preOrder(node->right, res, s);
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return vector<string> {};
vector<string> res;
string s = "";
preOrder(root, res, s);
return res;
}
No comments:
Post a Comment