【题目】
给定一个二叉树,返回所有从根节点到叶子节点的路径。说明: 叶子节点是指没有子节点的节点。
来源:leetcode
链接:https://leetcode-cn.com/problems/binary-tree-paths/
【示例】
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
【后序遍历】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :12.4 MB, 在所有 C++ 提交中击败了8.00%的用户
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<string> rs;
stack<TreeNode*> s,back;
public:
void deal(){
string str="";
while(!s.empty()){
back.push(s.top());
s.pop();
}
while(!back.empty()){
s.push(back.top());
str+=to_string(s.top()->val);
if(back.size()>1)
str+="->";
back.pop();
}
rs.push_back(str);
}
vector<string> binaryTreePaths(TreeNode* root) {
TreeNode* node=root,*last=NULL;
while(!s.empty()||node){
while(node){
s.push(node);
node=node->left;
}
if(!s.empty()){
node=s.top();
if(node->right&&node->right!=last){
node=node->right;
}else{
if(!node->left&&!node->right)
deal();
s.pop();
last=node;
node=NULL;
}
}
}
return rs;
}
};
【前序遍历的递归版】
执行用时 :8 ms, 在所有 C++ 提交中击败了56.64% 的用户
内存消耗 :14.1 MB, 在所有 C++ 提交中击败了8.00%的用户
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<string> rs;
public:
vector<string> binaryTreePaths(TreeNode* root) {
if(!root)
return {};
preOrder(root,to_string(root->val));
return rs;
}
void preOrder(TreeNode* root,string path){
if(!root->left&&!root->right){
rs.push_back(path);
return;
}
if(root->left)
preOrder(root->left,path+"->"+to_string(root->left->val));
if(root->right)
preOrder(root->right,path+"->"+to_string(root->right->val));
}
};
【前序遍历非递归版】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :12.3 MB, 在所有 C++ 提交中击败了12.00%的用户
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
stack<pair<TreeNode*,string>> s;
vector<string> rs;
vector<string> binaryTreePaths(TreeNode* root) {
if(!root)
return {};
pair<TreeNode*,string> node=pair<TreeNode*,string>(root,to_string(root->val));
s.push(node);
while(!s.empty()){
node=s.top();
s.pop();
if(node.first->right)
s.push(pair<TreeNode*,string>(node.first->right,
node.second+"->"+to_string(node.first->right->val)));
if(node.first->left)
s.push(pair<TreeNode*,string>(node.first->left,
node.second+"->"+to_string(node.first->left->val)));
if(node.first->left==NULL&&node.first->right==NULL)
rs.push_back(node.second);
}
return rs;
}
};