剑指 Offer 34. 二叉树中和为某一值的路径
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
示例 2:
输入:root = [1,2,3], targetSum = 5
输出:[]
示例 3:
输入:root = [1,2], targetSum = 0
输出:[]
提示:
树中节点总数在范围 [0, 5000] 内
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
class Solution {
List<List<Integer>> result =new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
if(root == null) {
return result;
}
ArrayList<Integer> temp =new ArrayList<>();
travel(root, 0 , target , temp);
return result;
}
public void travel (TreeNode root, int sum ,int target ,ArrayList temp){
if(sum+root.val == target && root.left == null && root.right == null){
temp.add(root.val);
result.add(new ArrayList(temp));
temp.remove(temp.size() - 1);
return;
}
temp.add(root.val);
if(root.left != null){
travel(root.left , sum+root.val , target , temp);
}
if(root.right != null){
travel(root.right , sum+root.val , target , temp);
}
temp.remove(temp.size() - 1);
}
}
剑指 Offer 36. 二叉搜索树与双向链表
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
为了让您更好地理解问题,以下面的二叉搜索树为例:
我们希望将这个二叉搜索树转化为双向循环链表。链表中的每个节点都有一个前驱和后继指针。对于双向循环链表,第一个节点的前驱是最后一个节点,最后一个节点的后继是第一个节点。
下图展示了上面的二叉搜索树转化成的链表。“head” 表示指向链表中有最小元素的节点。
特别地,我们希望可以就地完成转换操作。当转化完成以后,树中节点的左指针需要指向前驱,树中节点的右指针需要指向后继。还需要返回链表中的第一个节点的指针。
class Solution {
public Node treeToDoublyList(Node root) {
PriorityQueue<Node> pri = new PriorityQueue<Node>(new Comparator<Node>() {
public int compare(Node o1, Node o2) {
// TODO Auto-generated method stub
if(o1.val > o2.val){
return 1;
}
else if(o1.val < o2.val){
return -1;
}
else{
return 0;
}
}
});
Queue<Node> q=new LinkedList<>();
if(root==null){
return root;
}
q.add(root);
while(!q.isEmpty()){
Node n = q.poll();
if(n.left!=null){
q.add(n.left);
}
if(n.right != null){
q.add(n.right);
}
pri.add(n);
}
Node result = pri.poll();
if(pri.size()==0){
result.right=result;
result.left=result;
}
Node temp = result;
while(!pri.isEmpty()){
Node temp_node = pri.poll();
temp.right=temp_node;
temp_node.left=temp;
temp=temp_node;
if(pri.size()==0){
temp.right = result;
result.left = temp;
}
}
return result;
}
}
大意了啊,没有注意是二叉搜索树,先序遍历即可,不需要优先队列。
剑指 Offer 54. 二叉搜索树的第k大节点
给定一棵二叉搜索树,请找出其中第 k 大的节点的值。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/
1 4
2
输出: 4
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/
3 6
/
2 4
/
1
输出: 4
限制:
1 ≤ k ≤ 二叉搜索树元素个数
class Solution {
int result = 0;
int temp =0;
public int kthLargest(TreeNode root, int k) {
travel(root , k);
return result;
}
public void travel( TreeNode root , int k){
if(root.right != null){
travel(root.right , k);
}
temp += 1;
if(temp == k){
result = root.val;
return;
}
if(root.left != null){
travel(root.left , k);
}
}
}