zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    SAP 标准成本滚算小记
    记一次SAP新业务开发项目
    让人头疼的关键用户
    SAP GUI个性化设置
    惊心动魄的SAP S4客户额度调整运动
    最新.net和Java调用SAP RFC中间件下载
    那些年我遇到的ERP顾问
    【SAP业务模式】之STO(二):系统配置
    SAP S4系统创建Customer和Vendor的BAPI
    【SAP S/4 1511之变】:主数据之变
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8760643.html
Copyright © 2011-2022 走看看