LeetCode[9]|LeetCode[9] - Binary Tree Paths
【LeetCode[9]|LeetCode[9] - Binary Tree Paths】一幕了然. DFS把tree给过了.
用ArrayList存item比较方便,记得每次backtrack的时候把末尾的item去掉
list.remove(list.size() - 1);
/*
Given a binary tree, return all root-to-leaf paths.For example, given the following binary tree:1
/\\
23
\\
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 binaryTreePaths(TreeNode root) {
List rst = new ArrayList();
if (root == null) {
return rst;
}
ArrayList list = new ArrayList();
DFS(root, list, rst);
return rst;
}
public void DFS(TreeNode node, ArrayList list, List rst) {
list.add(node.val+"");
if(node.left == null && node.right == null) {
String str = "";
for (String s : list) {
str += s + "->";
}
rst.add(str.substring(0, str.length() - 2));
return;
}
if (node.left != null) {
DFS(node.left, list, rst);
list.remove(list.size() - 1);
}
if (node.right != null) {
DFS(node.right, list, rst);
list.remove(list.size() - 1);
}
}
}
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- Leetcode|Leetcode No.198打家劫舍
- [leetcode数组系列]1两数之和
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路
- LeetCode|LeetCode 876. 链表的中间结点