博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Binary Tree Paths
阅读量:6777 次
发布时间:2019-06-26

本文共 1256 字,大约阅读时间需要 4 分钟。

Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree:   1 /   \2     3 \  5All 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
binaryTreePaths(TreeNode root) {12 List
res = new ArrayList
();13 if (root == null) return res;14 helper(root, res, "");15 return res;16 }17 18 public void helper(TreeNode root, List
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 }

 

转载地址:http://tiseo.baihongyu.com/

你可能感兴趣的文章