letecode [257] - Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
题目大意:
给定二叉树,输出它的所有路径,用vector容器保存。
理 解:
采用递归的思想。
对根节点,若为空,则返回空容器。若根节点为叶节点,说明找到路径尾,添加该路径到容器。
对根节点,递归获得它的左右子树路径,再加入根节点值,添加到容器中。
代 码 C++:
/** * 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> res; string str; if(root==NULL) return res; str = to_string(root->val); if(root->left==NULL && root->right==NULL){ res.push_back(str); return res; } str += "->"; string res_str; vector<string> leftRes,rightRes; leftRes = binaryTreePaths(root->left); for(int i=0;i<leftRes.size();++i){ res_str = str + leftRes[i]; res.push_back(res_str); } rightRes = binaryTreePaths(root->right); for(int i=0;i<rightRes.size();++i){ res_str = str + rightRes[i]; res.push_back(res_str); } return res; } };
运行结果:
执行用时 :12 ms, 在所有C++提交中击败了78.14%的用户
内存消耗 :12.1 MB, 在所有C++提交中击败了72.05%的用户