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) {
            if(root == NULL)
                return res;
            stringstream ss;
            ss << root -> val;
            if((root -> left == NULL) && (root -> right == NULL))
            {
                res.push_back(ss.str());
                return res;
            }
            else
            {
                getPaths(root,ss.str());
            }
            return res;
        }
       
        void getPaths(TreeNode *root,string s)
        {
            if((root -> left == NULL) && (root -> right ==NULL))
            {
                res.push_back(s);
            }
            if(root -> left != NULL)
            {
                stringstream ss;
                ss << s << "->" << root -> left -> val;
                getPaths(root -> left , ss.str());
            }
            if(root -> right != NULL)
            {
                stringstream ss;
                ss << s << "->" <<  root -> right -> val;
                getPaths(root -> right , ss.str());
            }
        }
    private:
        vector<string> res;
    };

  • 相关阅读:
    delphi利用文件内存共享的简单小说阅读器
    Delphi中共享内存学习
    JavaWeb初学者配置数据库连接报错(此处是MSSQL)
    Delphi的Json学习之一
    Delphi记录类型指针的使用
    汇编——段寄存器
    SQL 标量函数-----日期函数 day() 、month()、year() 转载
    项目一总结 滚动监听
    一阶段项目总结 导航栏 滚动监听固定
    简单的 js手写轮播图
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5440096.html
Copyright © 2011-2022 走看看