• 257 Binary Tree Paths 二叉树的所有路径


    给定一个二叉树,返回从根节点到叶节点的所有路径。
    例如,给定以下二叉树:
       1
     /  
    2     3
     
      5
    所有根到叶路径是:
    ["1->2->5", "1->3"]

    详见:https://leetcode.com/problems/binary-tree-paths/description/

    Java实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res=new ArrayList<String>();
            if(root==null){
                return res;
            }
            helper(root,"",res);
            return res;
        }
        private void helper(TreeNode root,String out,List<String> res){
            out+=String.valueOf(root.val);
            if(root.left==null&&root.right==null){
                res.add(out);
            }
            if(root.left!=null){
                helper(root.left,out+"->",res);
            }
            if(root.right!=null){
                helper(root.right,out+"->",res);
            }
        }
    }
    

    C++实现:

    /**
     * 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) {
            vector<string> res;
            if(root)
            {
                helper(root,"",res);
            }
            return res;
        }
        void helper(TreeNode *root,string out,vector<string> &res)
        {
            out+=to_string(root->val);
            if(!root->left&&!root->right)
            {
                res.push_back(out);
            }
            if(root->left)
            {
                helper(root->left,out+"->",res);
            }
            if(root->right)
            {
                helper(root->right,out+"->",res);
            }
        }
    };
    

     参考:https://www.cnblogs.com/grandyang/p/4738031.html

  • 相关阅读:
    Android--多线程之Handler
    Android--Service之基础
    Android--UI之Fragment
    Android--多线程之图文混排
    python常用模块
    python应用之socket编程
    网络编程socket理论一
    pycharm Launching unittests with arguments
    python字符串格式化
    python数据类型之三
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8760643.html
Copyright © 2020-2023  润新知