给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入: 1 / \ 2 3 \ 5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
同样也可以用bfs
维护两个队列,一个队列用来存放当前的节点,一个队列用来存放节点构成的路径,每次从队列中弹出一个节点时,同时也弹出一个路径,如果当前节点有左孩子,就将左孩子连接到当前的路径中,路径入队;同样,如果当前节点有有孩子,也将当前节点的右孩子加入到当前的路径中,路径入队。 /** * 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; if(root == NULL) return res; queue<TreeNode*> q; queue<string> path; q.push(root); path.push(to_string(root->val)); while(!q.empty()){ auto temp_n = q.front(); auto temp_p = path.front(); q.pop(); path.pop(); if(temp_n->left == NULL && temp_n->right == NULL){ res.push_back(temp_p); } if(temp_n->left){ q.push(temp_n->left); path.push(temp_p + "->" + to_string(temp_n->left->val)); } if(temp_n->right){ q.push(temp_n->right); path.push(temp_p + "->" + to_string(temp_n->right->val)); } } return res; } };