二叉树的所有路径

来源:互联网 发布:支付宝mac 编辑:程序博客网 时间:2024/04/28 06:23

给一棵二叉树,找出从根节点到叶子节点的所有路径。

样例

给出下面这棵二叉树:

   1 /   \2     3 \  5

所有根到叶子的路径为:

[  "1->2->5",  "1->3"]
解题思路:递归遍历

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /**     * @param root the root of the binary tree     * @return all root-to-leaf paths     */    vector<string> binaryTreePaths(TreeNode* root) {        // Write your code here        vector<string> Paths;        if (root)        {            TreePaths(root,"",Paths);        }        return Paths;    }    void TreePaths(TreeNode* root,string temp,vector<string> &result)    {        temp += to_string(root->val);         if (!root->left && !root->right)        {            result.push_back(temp);        }        else        {            if (root->left)            {                TreePaths(root->left,temp+"->",result);            }            if (root->right)            {                TreePaths(root->right,temp+"->",result);            }        }    }};


0 0
原创粉丝点击