zoukankan      html  css  js  c++  java
  • [LeetCode] Binary Tree Paths

    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"]

    输出一个树的路径。使用递归的方法

    /**
     * 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 == nullptr)
                return res;
            binaryTreePathsCore(res, root, to_string(root->val));
            return res;
        }
        
        void binaryTreePathsCore(vector<string>& res, TreeNode* root, string s) {
            if (root->left == nullptr && root->right == nullptr) {
                res.push_back(s);
                return;
            }
            if (root->left != nullptr)
                binaryTreePathsCore(res, root->left, s + "->" + to_string(root->left->val));
            if (root->right != nullptr)
                binaryTreePathsCore(res, root->right, s + "->" + to_string(root->right->val));
        }
    };
    // 6 ms
  • 相关阅读:
    lua for循环
    多面体的欧拉公式
    流形(Manifold)初步
    Laplace算子和Laplacian矩阵
    多重网格方法(Multigridmethod)
    多重网格方法
    谷歌浏览器兼容IE插件
    伽辽金法
    共轭梯度法
    有限元分析
  • 原文地址:https://www.cnblogs.com/immjc/p/7448700.html
Copyright © 2011-2022 走看看