zoukankan      html  css  js  c++  java
  • 【LeetCode】257. 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:
        void recursiveTree(vector<string> &res, TreeNode* node, string str) {
            if (node->left == NULL && node->right == NULL) {
                res.push_back(str);
                return;
            }
            if (node->left != NULL) {
                recursiveTree(res, node->left, str + "->" + to_string(node->left->val));
            }
            if (node->right != NULL) {
                recursiveTree(res, node->right, str + "->" + to_string(node->right->val));
            }
        }
        
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> res;
            if (root == NULL) return res;
            recursiveTree(res, root, to_string(root->val));
            return res;
        }
    };
  • 相关阅读:
    PyQt5--Buttons
    PyQt5--Position
    PyQt5--ShowWindowCenter
    PyQt5--MessageBox
    PyQt5--CloseWindow
    PyQt5--ShowTips
    PyQt5---ChangeIcon
    PyQt5---firstwindow
    PyQt5--StatusBar
    PyQt5 的几个核心模块作用
  • 原文地址:https://www.cnblogs.com/jdneo/p/4753005.html
Copyright © 2011-2022 走看看