zoukankan      html  css  js  c++  java
  • 2021.2.5 刷题(二叉树的所有路径)

    题目链接:https://leetcode-cn.com/problems/binary-tree-paths/
    题目描述:
    给定一个二叉树,返回所有从根节点到叶子节点的路径。
    说明: 叶子节点是指没有子节点的节点。

    示例:

    解题:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        void getPaths(TreeNode* node, string path, vector<string> &vec)
        {
            if(node != nullptr)
            {
                path += to_string(node->val);                        //只有节点不空,加入路径中
                if(node->left == nullptr && node->right == nullptr) //叶子节点,表明该节点为路径终点
                {
                    vec.push_back(path);
                }else{                                              //还有孩子节点,继续向下查找叶子节点
                    path += "->";
                    getPaths(node->left, path, vec);
                    getPaths(node->right, path, vec);
                }
                
            }
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            vector<string> result;
            string path = "";
            if(root == nullptr)
                return result;
            getPaths(root, path, result);
            return result;
    
        }
    };
    
  • 相关阅读:
    js 多物体运动
    js运动 淡入淡出
    js运动 分享到
    正则 重复项最多得子项
    jq 拖拽
    jq 弹出窗口
    jq 选项卡
    jq 写法
    Codeforces 185A Plant( 递推关系 + 矩阵快速幂 )
    HDU 2604 Queuing( 递推关系 + 矩阵快速幂 )
  • 原文地址:https://www.cnblogs.com/ZigHello/p/14378431.html
Copyright © 2011-2022 走看看