leetcode第1997题特定深度节点链接
题目描述
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
package datastruct.tree.listdepth;
import java.util.LinkedList;
import java.util.Queue;
/**
* @date 2021/5/14 17:55
*/
public class ListOfDepth {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode[] listOfDepth(TreeNode tree) {
//递归计算出树的深度
int depth = getDepth(tree);
//初始化保存路径数组
ListNode[] listNodes = new ListNode[depth];
//采用队列临时存放树上每一层的节点
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(tree);
int index = 0;
//循环终止条件:树的最大深度
while (!queue.isEmpty()) {
int size = queue.size();
ListNode newhead = new ListNode(0);
ListNode indexNode = newhead;
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
indexNode.next = new ListNode(poll.val);
indexNode = indexNode.next;
if (poll.left != null) {
queue.offer(poll.left);
}
if (poll.right != null) {
queue.offer(poll.right);
}
}
listNodes[index++] = newhead.next;
}
return listNodes;
}
private int getDepth(TreeNode treeNode) {
if (treeNode == null) {
return 0;
}
return Math.max(getDepth(treeNode.left), getDepth(treeNode.right)) + 1;
}
}
leetcode第1930题二叉树中和为某一个值的路径
题目描述:
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
package datastruct.tree.treeroad;
import java.util.LinkedList;
import java.util.List;
/**
*回朔法 搜索路径根节点到叶子节点上的值之和等于指定数值大小
* @date 2021/5/14 15:05
*/
public class SearchTreeRoad {
private List<List<Integer>> roads = new LinkedList<>();
private LinkedList<Integer> road = new LinkedList<>();
public static class Node {
private Integer val;
private Node left;
private Node right;
public Node(Integer val) {
this.val = val;
}
public Integer getVal() {
return val;
}
public void setVal(Integer val) {
this.val = val;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
public List<List<Integer>> getPath(Node node, Integer target) {
search(node, target);
return roads;
}
public void search(Node node, Integer target) {
//递归终止条件
if (node == null) {
return;
}
road.add(node.getVal());
target = target - node.getVal();
//根节点到叶子节点路径上各节点之和等于指定值
if (target == 0 && node.getLeft() == null && node.getRight() == null) {
roads.add(new LinkedList<>(road));
}
//递归子问题
search(node.left, target);
search(node.right, target);
//回溯
road.removeLast();
}
}