LeetCode:Binary Tree Paths
来源:互联网 发布:中文域名管理中心 编辑:程序博客网 时间:2024/04/29 11:39
问题描述:
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"]
思路:
简单的二叉树遍历,遍历的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入结果中。
JAVA代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { List<String> res = new ArrayList<String>(); public List<String> binaryTreePaths(TreeNode root) { if(root != null){ findpath(root,String.valueOf(root.val));//一个string参数转换为Integer类型 } return res; } private void findpath(TreeNode n,String path){ if(n.left == null && n.right == null){ res.add(path); } if(n.left != null){ findpath(n.left,path + "->" + n.left.val); } if(n.right != null){ findpath(n.right,path + "->" + n.right.val); } }}
0 0
- Leetcode: Binary Tree Paths
- [LeetCode] Binary Tree Paths
- [Leetcode]Binary Tree Paths
- leetcode:Binary Tree Paths
- [leetcode] Binary Tree Paths
- Leetcode: Binary Tree Paths
- LeetCode:Binary Tree Paths
- leetcode Binary Tree Paths
- leetcode Binary Tree Paths
- LeetCode:Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode || Binary Tree Paths
- *LeetCode-Binary Tree Paths
- Binary Tree Paths -- leetcode
- LeetCode---Binary Tree Paths
- leetcode-Binary Tree Paths
- windows 批处理命令与CMD 命令
- TinyOS的个人见解2之ncc编译过程
- 欢迎使用CSDN-markdown编辑器
- 哈理工院赛热身赛 --- 骑士相遇
- Java多线程-线程的调度(守护线程)
- LeetCode:Binary Tree Paths
- 贪心算法-汽车加油问题
- C语言学习笔记(16) c语言字符串分析
- 面积
- Receiving login prompt using integrated windows authentication
- linux 下java环境搭建
- 大小写转换
- css 创建水平导航条
- 检查宿舍卫生