LeetCode: 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

解题思路 —— 递归求解

分别求出左右子树的 Binary Tree Paths,然后在前面加上根节点的值。

AC 代码

/**
 * 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)
    {
        if(root == nullptr)
        {
            return {};
        }
        
        // 分别计算左右子树的 binaryTreePaths
        vector<string> leftChildTreePath = binaryTreePaths(root->left);
        vector<string> rightChildTreePath = binaryTreePaths(root->right);
        
        // 分别在左右子树的 binaryTreePaths 前面加上 root->val
        vector<string> rootTreePath;
        string rootVal(to_string(root->val));
        for(size_t i = 0; i < leftChildTreePath.size(); ++i)
        {
            rootTreePath.push_back(rootVal+"->"+leftChildTreePath[i]);
        }
        for(size_t i = 0; i < rightChildTreePath.size(); ++i)
        {
            rootTreePath.push_back(rootVal+"->"+rightChildTreePath[i]);
        }     
        
        if(rootTreePath.empty())
        {
            rootTreePath.push_back(rootVal);
        }
        
        return rootTreePath;
    }
};