leetcode

    xiaoxiao2021-03-25  105

    题目:

    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"] 就是一个深搜,关键点是,什么时候把搜到的加上去。它这个是每个叶子都有一条深搜的道路。也就是在递归的时候就将结点加上去了,于是就有了所有的道路。当到叶子的时候把这个当前的道路加到要输出的总和中,然后继续下面的递归。

    然后要注意的是他给的root可能是空的,要先判断一下。

    还有就是int要转成string,中间还要加->

    贴代码:

    /** * 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> outstring; if(root==NULL) return outstring; search(outstring,root,to_string(root->val)); return outstring; } void search(vector<string>&outstring, TreeNode* root, string value){ if(root->left==NULL && root->right == NULL){ outstring.push_back(value); } if(root->left != NULL){ search(outstring, root->left, value + "->" + to_string(root->left->val)); } if(root->right != NULL){ search(outstring, root->right, value + "->" + to_string(root->right->val)); } return; } };

    转载请注明原文地址: https://ju.6miu.com/read-17246.html

    最新回复(0)