class Solution {
public:
string make_path(stack<TreeNode *> st){
string s,temp;
TreeNode *pre=st.top()->left;
while(!st.empty()){
TreeNode *cur=st.top();
if(cur->left!=pre&&cur->right!=pre){
st.pop();
continue;
}
stringstream ss;
ss<<cur->val;
temp=ss.str();
if(s==""){
s=temp;
}
else{
s=temp+"->"+s;
}
pre=cur;
}
return s;
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
string str;
if(root==NULL){
return res;
}
stack<TreeNode *> st;
st.push(root);
TreeNode *pre=root;
while(!st.empty()){
TreeNode *cur=st.top();
if(pre!=cur->left&&pre!=cur->right){
if(cur->right!=NULL){
st.push(cur->right);
}
if(cur->left!=NULL){
st.push(cur->left);
}
if(cur->left==NULL&&cur->right==NULL){
res.push_back(make_path(st));
pre=cur;
st.pop();
}
}
else{
pre=cur;
st.pop();
}
}
}
};
LeetCode - 257 Binary Tree Paths
最新推荐文章于 2024-06-04 10:44:44 发布