# Sword finger offer plan 15 (search and backtracking algorithm medium) — Java

Time：2021-12-4

## 1.1 topic 1

Sword finger offer 54. The k-th node of the binary search tree

## 1.2 solution

Res and K are set as global variables, and then start traversing the binary search tree,
Because it is a binary search tree, it starts from the right node,
Each traversal determines whether to reach the node.
Each node is -k and knows the arrival node.

## 1.3 code

class Solution {
int res,k;
public int kthLargest(TreeNode root, int k) {
this.k=k;
dfs(root);
return res;
}

public void dfs(TreeNode root){
if(root==null) return ;
dfs(root.right);
if(k==0) return;
if(--k==0) res=root.val;
dfs(root.left);
}
}

## 2.1 topic 2

Sword finger offer 36. Binary search tree and bidirectional linked list

## 2.2 solution

Depth first search, start assignment through the front and back nodes,
During search, the node is traversed in middle order. If the node is not empty,
Then the right of the pre node is the current node, and the left of the node is pre
Then the pre node becomes the current node and continues to traverse to the next node

## 2.3 code

class Solution {
public Node treeToDoublyList(Node root) {
if(root == null) return null;
dfs(root);
}
void dfs(Node cur) {
if(cur == null) return;
dfs(cur.left);
if(pre != null) pre.right = cur;
cur.left = pre;
pre = cur;
dfs(cur.right);
}
}

## 3.1 topic 3

Sword finger offer 34. A path with a certain value in a binary tree

## 3.2 solution

It’s a bit like going back and adding and subtracting branches
If the leaf node is reached and the route node value is the target value, it will be added to the list

At the end of this step, you need to delete the added value to enter the next stage.

## 3.3 code

class Solution {
public List> pathSum(TreeNode root, int sum) {
recur(root, sum);
return res;
}
void recur(TreeNode root, int tar) {
if(root == null) return;
tar -= root.val;
if(tar == 0 && root.left == null && root.right == null)