标签:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / 2 3 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
前序递归即可。
/** * 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: vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; if(root == NULL) return result; string path; binaryTreePaths(root , result , path); return result; } void binaryTreePaths(TreeNode* root , vector<string> &result , string path) { if(root == NULL) return; if(path.empty()) path += to_string(root->val); else { path += "->"; path += to_string(root->val); } if(root->left == NULL && root->right == NULL) { result.push_back(path); return; } binaryTreePaths(root->left , result , path); binaryTreePaths(root->right , result , path); } };
/** * 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: vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; if(root == NULL) return result; string path; binaryTreePaths(root , result , path); return result; } void binaryTreePaths(TreeNode* root , vector<string> &result , string path) { if(root == NULL) return; if(root->left == NULL && root->right == NULL) { result.push_back(path + to_string(root->val)); return; } binaryTreePaths(root->left , result , path + to_string(root->val) + "->"); binaryTreePaths(root->right , result , path + to_string(root->val) + "->"); } };
版权声明:转载请注明出处。
LeetCode OJ 之 Binary Tree Paths(二叉树路径)
标签:
原文地址:http://blog.csdn.net/u012243115/article/details/48133743