36.二叉树中和为某一值的路径
题目:
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。叶子节点 是指没有子节点的节点。
题解:
前序遍历-----
recur
函数
- 将node存入path中,同时更新sum的值,令sum -= root.val;
- 如果此时sum == 0 且 该节点为叶子节点,则该路径满足题目条件,存入
res
中- 注意 由于list结构在传递过程中传递的是内存地址,因此在存入res操作应该使用
res.add(new LinkedList<>(path));
而不是res.add(path)
;
- 注意 由于list结构在传递过程中传递的是内存地址,因此在存入res操作应该使用
- 带着更新的sum开始递归遍历其左右子树;
- 回溯: 在回溯时注意将当前path的尾部元素去除,即去掉该层递归在path中添加的元素,回溯至上一层重新开始。
class Solution {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
recur(root,target);
return res;
}
void recur(TreeNode root, int sum){
if (root == null) return;
path.add(root.val);
sum -= root.val;
if (sum == 0 && root.left == null && root.right == null) res.add(new LinkedList<>(path));
recur(root.left,sum);
recur(root.right,sum);
path.removeLast();
}
}
37.二叉搜索树与双向链表
题目:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
题解:
- 通过中序遍历
inorder
函数遍历二叉树节点,将节点存入Queue中; - 对Queue中的节点进行遍历,修改左右指针;
- 为了形成循环链表,引入空头节点
res
帮助连接。
class Solution {
Queue<Node> queue = new LinkedList<>();
public Node treeToDoublyList(Node root) {
if (root == null) return null;
inorder(root);
Node cur = new Node();
Node res = cur;
while (!queue.isEmpty()){
Node remove = queue.remove();
cur.right = remove;
remove.left = cur;
//当cur.right == null时,说明此时为最后一个节点,cur指针不再移动,
//即cur此时指向最后节点,方便与头节点进行循环链接
if(cur.right != null) cur = cur.right;
}
cur.right = res.right;
res.right.left = cur;
return res.right;
}
void inorder(Node root){
if (root == null) return;
inorder(root.left);
queue.add(root);
inorder(root.right);
}
}
38.二叉搜索树的第k大节点
题目:
给定一棵二叉搜索树,请找出其中第 k
大的节点的值。
题解:
- 中序遍历的另一种形式,访问顺序为
右子树-->根节点-->左子树
,最终返回的list为递减序列; - 返回list.get(k - 1);
class Solution {
List list = new ArrayList<Integer>();
public int kthLargest(TreeNode root, int k) {
inorder(root);
return (int)list.get(k - 1);
}
void inorder(TreeNode root){
if (root == null) return;
inorder(root.right);
list.add(root.val);
inorder(root.left);
}
}
紧动脑子,慢张嘴,只讲立场,不讲是非。