题目介绍
力扣257题:leetcode-cn.com/problems/bi…
方法一:递归 + 回溯
首先我们可以知道,找到了叶子节点,也就找到了一条路径,叶子节点的判断条件很简单,就是左子树跟右子树都为空,所以思路还是比较简单的,代码如下;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<String> result = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root == null) {
return result;
}
List<Integer> paths = new ArrayList<>();
preOrder(root, paths);
return result;
}
public void preOrder(TreeNode root, List<Integer> paths) {
paths.add(root.val);
//找到了叶子节点,即找到了一条路径
if (root.left == null && root.right == null) {
StringBuilder sb = new StringBuilder();
for (Integer i : paths) {
sb.append(i).append("->");
}
//去掉最后一个多余的->
sb.delete(sb.length() - 2, sb.length());
result.add(sb.toString());
return;
}
if (root.left != null) {
preOrder(root.left, paths);
//回溯
paths.remove(paths.size() - 1);
}
if (root.right != null) {
preOrder(root.right, paths);
//回溯
paths.remove(paths.size() - 1);
}
}
}
方法二:迭代
代码如下:
// 解法2
class Solution {
/**
* 迭代法
*/
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root == null)
return result;
Stack<Object> stack = new Stack<>();
// 节点和路径同时入栈
stack.push(root);
stack.push(root.val + "");
while (!stack.isEmpty()) {
// 节点和路径同时出栈
String path = (String) stack.pop();
TreeNode node = (TreeNode) stack.pop();
// 若找到叶子节点
if (node.left == null && node.right == null) {
result.add(path);
}
//右子节点不为空
if (node.right != null) {
stack.push(node.right);
stack.push(path + "->" + node.right.val);
}
//左子节点不为空
if (node.left != null) {
stack.push(node.left);
stack.push(path + "->" + node.left.val);
}
}
return result;
}
}