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

  • 相关阅读:
    MySQL性能优化的最佳20+条经验
    memcached demo 应用例子
    关于 MySQL 主从复制的配置(转)
    java date 日期 利用 Calendar 实现增加一年月日时分秒
    Struts2中s:set标签和s:if标签小结
    hibernate oracle 配置序列 实现自动增长
    mysql5.1.47二进制版本的安装(转)
    Confluence3.4的安装和配置
    linux MemCache安装手册
    Java实现文件拷贝的4种方法(转)
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5440096.html
Copyright © 2011-2022 走看看