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;
    };

  • 相关阅读:
    Linux 简介
    5设计模式之桥接模式(结构模式)
    2设计模式之简单工厂模式(构造模式)
    3异步和多线程
    1设计模式之单例模式
    性能测试知多少---吞吐量
    NumberFormat DecimalFormat
    Java 005 枚举
    log4j
    Java Basic
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5440096.html
Copyright © 2011-2022 走看看