首页 > 其他 > 详细

Leetcode480-Binary Tree Paths-Easy

时间:2019-04-06 14:39:47      阅读:148      评论:0      收藏:0      [点我收藏+]

480. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

Example

Example 1:

Input:

   1
 /   2     3
   5

Output:


[
  "1->2->5",
  "1->3"
]

Example 2:

Input:

   1
 /   
2     
 

Output:


[
  "1->2"
]

注意:

因为题目的output格式 "1 -> 2",(有箭头),所以用String来存储每一个path。

递归法代码:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root of the binary tree
     * @return: all root-to-leaf paths
     */
    ArrayList<String> result;
    
    public List<String> binaryTreePaths(TreeNode root) {
        result = new ArrayList<String>();
        if (root == null) {
            return result;
        }
         
        String path = String.valueOf(root.val);
        helper(root, path);
        return result;
    }
    public void helper(TreeNode root, String path) {
        
        if (root.left == null && root.right == null) {
            result.add(path);
            return;
        }
        
        if (root.left != null) {
            helper(root.left, path + "->" + String.valueOf(root.left.val));
        }
        
        if (root.right != null) {
            helper(root.right, path + "->" + String.valueOf(root.right.val));
        }
    }    
}

 

Leetcode480-Binary Tree Paths-Easy

原文:https://www.cnblogs.com/Jessiezyr/p/10661656.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!