What is the meaning of input [1,2,3],can anyone tell my what is wrong with my code?


  • 0
    A

    my code get the error :Runtime error Last executed input:[1,2,3]

       class Solution {
       public:
               void SearchLeafs(TreeNode *root,TreeNode *leafHead,map<string,string> &parent)
        {
    	if (!root->left&&!root->right)
    	{
    		//insert into the list header
    		TreeNode * t=leafHead->right;
    		leafHead->right=root;
    		root->right=t;
    		return;
    	}
    	char *intPStr=new char(50),*intCStr=new char(50);
    	if (root->left)
    	{
    		sprintf(intPStr,"%d",root->val);
    		sprintf(intCStr,"%d",root->left->val);
    		string parentstr( intPStr),childstr(intCStr);
    
    		parent[childstr]=parentstr;
    		SearchLeafs(root->left,leafHead,parent);
    	}
    	if (root->right)
    	{
    		sprintf(intPStr,"%d",root->val);
    		sprintf(intCStr,"%d",root->right->val);
    		string parentstr( intPStr),childstr(intCStr);
    		parent[childstr]=parentstr;
    		SearchLeafs(root->right,leafHead,parent);
    	}
       }
          vector<string> binaryTreePaths(TreeNode* root)
      {
    	vector<string> paths;
    	if (!root)
    	{
    		return paths;
    	}	
    	TreeNode *leafHead=new TreeNode(0);
    	map<string,string> parent;
    	SearchLeafs(root,leafHead,parent);
    	char * intCStr=new char(50);
    	while (leafHead->right)
    	{
    		sprintf(intCStr,"%d",leafHead->right->val);
    		string chldstr(intCStr);
    		string path=chldstr;
    		while (parent.find(chldstr)!=parent.end())
    		{
    			path.insert(0,parent[chldstr]+"->");
    			chldstr=parent[chldstr];
    		}
    		leafHead=leafHead->right;
    		paths.insert(paths.begin(),path);
    	}
    	return paths;
          }
    

    };


  • 0

    The meaning of [1, 2, 3] is that a tree with root 1 and left child 2, right child 3.


  • 0
    A

    thank you ! then the result should be 1->2,1->3,my program result is same as it,why it give runtime error?Do you have any idea


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.