Short and clear c++ dfs solution


  • 11
    V
    vector<string> binaryTreePaths(TreeNode* root) {
    	vector<string> res;
    	help(res, root, "");
    	return res;
    }
    void help(vector<string>& res, TreeNode* root, string pre) {
    	if (!root)
    		return;
    	if (!root->left && !root->right) {
    		res.push_back(pre + to_string(root->val));
    		return;
    	}
    	help(res, root->left, pre + to_string(root->val) + "->");
    	help(res, root->right, pre + to_string(root->val) + "->");
    }

  • 0
    L
    use dfs  
    class Solution {
    public:
    	void getTreePaths(vector<string> & result, TreeNode *node, string tmp) {
    		if (!node->left && !node->right) {
    			result.push_back(tmp);
    			return;
    		}
    		if (node->left) {
    			getTreePaths(result, node->left, tmp + "->" + to_string(node->left->val));
    		}
    		if (node->right) {
    			getTreePaths(result, node->right, tmp + "->" + to_string(node->right->val));
    		}
    	}
    	vector<string> binaryTreePaths(TreeNode* root) {
    		vector<string> res;
    		if (!root)
    			return res;
    
    			getTreePaths(res, root, to_string(root->val));
    			return res;
    		
    	}
    };

Log in to reply
 

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