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"]
     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<String> binaryTreePaths(TreeNode root) {
    12         List<String> res = new ArrayList<String>();
    13         if (root == null) return res;
    14         helper(root, res, "");
    15         return res;
    16     }
    17     
    18     public void helper(TreeNode root, List<String> res, String item) {
    19         if (root.left == null && root.right == null) {
    20             if (item.length() == 0) {
    21                 res.add("" + root.val);
    22             }
    23             else {
    24                 res.add(item + "->" + root.val);
    25             }
    26             return;
    27         }
    28         if (root.left != null) 
    29             helper(root.left, res, item.length()==0? ""+root.val : item+"->"+root.val);
    30         if (root.right != null)
    31             helper(root.right, res, item.length()==0? ""+root.val : item+"->"+root.val);
    32         
    33     }
    34 }
  • 相关阅读:
    卡嘉mysql命令
    Go并发控制和超时控制
    sync包介绍
    Golang-RSA加密解密-数据无大小限制
    GO json 如何转化为 map 和 struct
    go之gorm
    go mod 生成 vendor
    go语言中找&和*区别
    Swoole的process通信的方式
    centos安装python3
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5066289.html
Copyright © 2011-2022 走看看