博客
关于我
LeetCode——Binary Tree Paths
阅读量:795 次
发布时间:2023-01-31

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

Description:

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"]
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List
paths; public List
path; public List
binaryTreePaths(TreeNode root) { paths = new ArrayList
(); path = new ArrayList
(); getAllPath(root); return paths; } public void getAllPath(TreeNode node) { // 1 // / \ // 2 3 ["1->2->5", "1->3"] // \ // 5 if(node == null) { return ; } path.add(node.val); if(node.left==null && node.right==null) { StringBuilder onePath = new StringBuilder(); for(int i=0; i
"); onePath.append(path.get(i)); } paths.add(onePath.toString()); } getAllPath(node.left); getAllPath(node.right); path.remove(path.size() - 1); }}

 

 

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

你可能感兴趣的文章
leetcode380. Insert Delete GetRandom O(1)
查看>>
LeetCode502
查看>>
leetcode507
查看>>
LeetCode7.整数反转 JavaScript
查看>>
Leetcode: Group Anagrams
查看>>
Leetcode: Remove Duplicates from Sorted Array II
查看>>
Leetcode: Spiral Matrix II
查看>>
LeetCode: String to Integer (atoi)
查看>>
Leetcode:454. 4Sum II
查看>>
leetcode:Minimum Depth of Binary Tree【Python版】
查看>>
LeetCode:Restore IP Addresses
查看>>
LeetCode:Subsets I II
查看>>
LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)
查看>>
LeetCode——Unique Paths
查看>>
LeetCode二叉树从上至下路径问题总结(112.113.437.129)
查看>>
leetcode出现cannot find symbol [in __Driver__.java]
查看>>
LeetCode动态规划训练营(1~5天)
查看>>
LeetCode哈希表+字符类的题目总结
查看>>
LeetCode商汤专场——第216场周赛题解
查看>>
LeetCode地平线专场——第308场周赛题解
查看>>