day15

1.剑指 Offer 34. 二叉树中和为某一值的路径

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<vector<int> > res;
15     vector<int> path;
16 
17     vector<vector<int>> pathSum(TreeNode* root, int target) {
18        dfs(root,target);
19        return res;
20     }
21 
22     void dfs(TreeNode* root,int target){
23        if(! root) return;
24        path.push_back(root -> val);
25        target -= root -> val;
26        if(target == 0 && root -> left == nullptr && root -> right == nullptr)
27            res.push_back(path);
28        if(root -> left) dfs(root -> left,target);
29        if(root -> right) dfs(root -> right,target);
30        path.pop_back();
31     }
32 };

 

2.剑指 Offer 36. 二叉搜索树与双向链表

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4 public:
 5     int val;
 6     Node* left;
 7     Node* right;
 8 
 9     Node() {}
10 
11     Node(int _val) {
12         val = _val;
13         left = NULL;
14         right = NULL;
15     }
16 
17     Node(int _val, Node* _left, Node* _right) {
18         val = _val;
19         left = _left;
20         right = _right;
21     }
22 };
23 */
24 class Solution {
25 public:
26     Node* head,*pre;
27 
28     Node* treeToDoublyList(Node* root) {
29         if(root == nullptr) return root;
30         dfs(root);
31         head -> left = pre;
32         pre -> right = head;
33         return head;
34     }
35     
36     void dfs(Node* root){
37         if(root == nullptr) return;
38         dfs(root -> left);
39         if(pre != nullptr) pre -> right = root;
40         else head = root;
41         root -> left = pre;
42         pre = root;
43         dfs(root -> right);
44     }
45 };

 

3.剑指 Offer 54. 二叉搜索树的第 k 大节点

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int res;
13 
14     int kthLargest(TreeNode* root, int k) {
15         dfs(root,k);
16         return res;
17     }
18     
19     void dfs(TreeNode* root,int& k){
20         if(root == nullptr) return;
21         dfs(root -> right,k);
22         if(k == 0) return;   //避免找到res值之后 的一些无效遍历
23         if(k == 1) res = root -> val;
24         k --;
25         dfs(root -> left,k);
26     }
27 };

 

posted @ 2022-07-11 16:21  balabalahhh  阅读(24)  评论(0)    收藏  举报