Leetcode 257. 二叉树的所有路径
这个题我做了一早上,原本的思路是通过二叉树的中序遍历完成,但是出错了,不明白问题在哪里,先放着吧,将来回头再看。网上的解法是递归,本质上是中序遍历。
1. 我的解法(中序遍历)
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
stack<TreeNode *> nodes;
vector<string> reval;
if(!root) return reval;
int directionFlag = 0;
string str = "->";
while(true)
{
travelAlongLeft(root, str, nodes, directionFlag);
if(nodes.empty()) return reval;
TreeNode * temp = nodes.top();
nodes.pop();
++directionFlag;
if(temp->right == nullptr)
{
str = str.substr(2);
reval.push_back(str);
str.erase(str.end()-directionFlag);
}
else
root = root->right;
}
}
void travelAlongLeft(TreeNode* root, string str, stack<TreeNode *> & nodes, int& directionFlag)
{
directionFlag = 0 ;
while(root)
{
str.append(to_string(root->val) + "->");
nodes.push(root);
root = root->left;
}
}
};
2. 网上的递归解法
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string>Paths;
if(root==NULL) return Paths;
ff(root,Paths,to_string(root->val) );
return Paths;
}
void ff(TreeNode *root,vector<string>&Paths,string strPaths){
if(root->left==NULL&&root->right==NULL){
Paths.push_back(strPaths);
return;
}
if(root->left!=NULL)
ff(root->left,Paths,strPaths+"->"+to_string(root->left->val) );
if(root->right!=NULL)
ff(root->right,Paths,strPaths+"->"+to_string(root->right->val) );
}
};