# Leetcode面T4(1-9)树

### Q4.1 节点间通路

class Solution {
public boolean findWhetherExistsPath(int n, int[][] graph, int start, int target) {
map = new HashMap<>();
visited = new int[n];
for(int[] edge:graph){
List<Integer> list = map.getOrDefault(edge[0], new ArrayList<>());
map.put(edge[0], list);
}
return dfs(start, target);
}
private boolean dfs(int start, int target){
if(start == target)
return true;
visited[start] = 1;
if(map.get(start) == null)
return false;
List<Integer> list = map.get(start);
for(int i:list){
if(visited[i] == 0){
if(dfs(i, target))
return true;
}
}
visited[start] = 1;
return false;
}

private HashMap<Integer, List<Integer>> map;
private int[] visited;
}

### Q4.2 最小高度树

0
/ \
-3   9
/   /
-10  5

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode root;
root=f(nums,0,nums.length-1);
return root;
}
public TreeNode f(int[] nums,int x,int y){
if(x>y) return null;

TreeNode root=new TreeNode();
int s=(x+y)/2;
root.val=nums[s];
root.left=f(nums,x,s-1);
root.right=f(nums,s+1,y);

return root;
}
}

### Q4.3 特定深度节点链表

1
/  \
2    3
/ \    \
4   5    7
/
8

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode[] listOfDepth(TreeNode root) {
if (root == null) {
return null;
}
//BFS中的队列
Queue<TreeNode> queue = new LinkedList<>();
//先把根节点入队，然后执行“弹一个，加n个”
//存放每个链表第一个有实际值(非哑元)节点的容器,ArrayList实际上是一个可变长的数组
List<ListNode> list = new ArrayList<>();
//只要队列中还有元素就要不停的出队，直到队列中的所有元素都已出队
while (!queue.isEmpty()) {
//当前队列的长度，即当前层元素的总个数
int size = queue.size();
//链表的头结点，不放实际的值（哑元）
ListNode head = new ListNode(0);
//链表移动指针，让它始终指向当表链表的最后一个元素
ListNode p = head;
//将当前层的节点逐个出队，把出队节点的子节点入队
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
//链表元素追加
p.next = new ListNode(poll.val);
//指针向后移动一个元素，使p指向链表末尾
p = p.next;
if (poll.left != null) {
//当前出队的节点有左孩子，则左孩子入队
}
if (poll.right != null) {
//当前出队的节点有右孩子，则右孩子入队
}
}
//for循环走完后就遍历完了一层，将存储该层节点的链表第一个有实际值的节点入队
}
//将可变长的数组转化成定长数组（因为函数的返回值要求了返回一个定长数组ListNode[]）
return list.toArray(new ListNode[list.size()]);
}
}


### Q4.4  检查平衡性

3
/ \
9  20
/  \
15   7

1
/ \
2   2
/ \
3   3
/ \
4   4

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
int x=depth(root.left);
int y=depth(root.right);
if(x-y>=-1&&x-y<=1){
boolean m=isBalanced(root.left);
boolean n=isBalanced(root.right);
return m&&n;
}else{
return false;
}

}
public int depth(TreeNode root){
if(root==null) return 0;
return Math.max(depth(root.left),depth(root.right))+1;
}
}

### Q4.5  合法二叉搜索树

2
/ \
1   3

5
/ \
1   4
/ \
3   6

根节点的值为 5 ，但是其右子节点值为 4 。

• 一个节点的左子树上节点的值都小于自身的节点值
• 一个节点的右子树上节点的值都小于自身的节点值
• 所有节点的左右子树都必须是二叉搜索树

采用递归中序遍历方法依次比较当前节点值和后一个节点值的大小，若当前节点值大于等于后一个节点值，则不是 二叉搜索树：

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {

Integer pre = null;

public boolean isValidBST(TreeNode root) {
if (root == null) return true;
if (isValidBST(root.left)) {
if (pre == null) pre = root.val;
else {
if (root.val <= pre) return false;
else pre = root.val;
}
return isValidBST(root.right);
}
return false;

}
}

### Q4.8  首个共同祖先

3
/ \
5   1
/ \ / \
6  2 0  8
/ \
7   4

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)
return null;
if(p == root || q == root)
return root;
TreeNode l = lowestCommonAncestor(root.left, p, q);
TreeNode r = lowestCommonAncestor(root.right, p, q);
if(l != null && r != null)
return root;
return l == null ? r : l;
}
}

### Q4.9  二叉搜索树序列

2
/ \
1   3

[
[2,1,3],
[2,3,1]
]

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> BSTSequences(TreeNode root) {
res = new LinkedList<>();
if(root == null){
return res;
}
getSequences(root, list, path);
return res;
}
private void getSequences(TreeNode root, LinkedList<TreeNode> list, LinkedList<Integer> path){
if(root == null){
return;
}
if(root.left != null)
if(root.right != null)
if(list.isEmpty()){
return;
}
int len = list.size();
for(int i = 0; i < len; ++i){
TreeNode cur = list.get(i);
list.remove(i);
getSequences(cur, new LinkedList<>(list), path);
path.removeLast();
}
}
private List<List<Integer>> res;
}


### Q4.10  检查子树

输入：t1 = [1, 2, 3], t2 = [2]
输出：true

输入：t1 = [1, null, 2, 4], t2 = [3, 2]
输出：false

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public static boolean isSame(TreeNode t1, TreeNode t2) {
//当同时到达叶子节点的后继（都为空），依然没返回false，就返回true
if (t1 == null && t2 == null) {
return true;
}
//待比较的两个节点一个为空，另一个不为空，说明这两棵树不相等
if (t1 == null || t2 == null) {
return false;
}
//如果待比较的两个节点都不为空，就比较它们的值是否相等，如果值相等就继续判断它们的左、右子树是否相等
return t1.val == t2.val && isSame(t1.left, t2.left) && isSame(t1.right, t2.right);
}
public boolean checkSubTree(TreeNode t1, TreeNode t2) {
//如果遍历到达的节点为空，则判断t2是否也为空，若是返回true，不是返回false
if (t1 == null) {
return t2 == null;
}
//遍历t1的每一个节点，看能否找到一棵子树与t2相同
return isSame(t1, t2) || (checkSubTree(t1.left, t2) || checkSubTree(t1.right, t2));
}
}


### Q4.12  求和路径

5
/ \
4   8
/   / \
11  13  4
/  \    / \
7    2  5   1

3

class Solution {

public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
return helper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}

private int helper(TreeNode node, int sum) {
if (null == node) {
return 0;
}
sum -= node.val;
int count = sum == 0 ? 1 : 0;
count += helper(node.left, sum);
count += helper(node.right, sum);
return count;
}
}

02-25 353

06-15 1003
01-10 177
08-27 1722
09-22 2360
01-23 2753
05-19
12-20
09-18
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客