C++實現兩數之和 IV - 輸入為二叉搜尋樹
假設我們有一個二叉搜尋樹和一個目標值;我們需要檢查二叉搜尋樹中是否存在兩個元素,它們的和等於給定的目標值。
因此,如果輸入如下所示:
則輸出為True。
為了解決這個問題,我們將遵循以下步驟:
定義一個數組v
定義一個函式inorder(),它將接收根節點作為引數:
如果根節點為空,則:
返回
inorder(根節點的左子樹)
將根節點的值插入到v中
inorder(根節點的左子樹)
inorder(根節點的右子樹)
定義一個函式findnode(),它將接收k作為引數:
n := v的大小
當 i < j 時,執行以下操作:
t := v[i] + v[j]
如果t等於k,則:
返回true
如果t < k,則:
(將i增加1)
否則
(將j減少1)
返回false
在主方法中執行以下操作:
inorder(root)
對陣列v進行排序
返回findnode(k)
示例
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; } else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; } else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } class Solution { public: vector<int> v; void inorder(TreeNode* root){ if (root == NULL || root->val == 0) return; inorder(root->left); v.push_back(root->val); inorder(root->right); } bool findnode(int k){ int n = v.size(), i = 0, j = n - 1; while (i < j) { int t = v[i] + v[j]; if (t == k) return true; if (t < k) i++; else j--; } return false; } bool findTarget(TreeNode* root, int k){ inorder(root); sort(v.begin(), v.end()); return findnode(k); } }; main(){ Solution ob; vector<int> v = {5,3,6,2,4,NULL,7}; TreeNode *root = make_tree(v); cout << (ob.findTarget(root, 9)); }
線上演示
{5,3,6,2,4,NULL,7},9
輸入
1
列印頁面