檢核是否有2個樹值加總等於目標值
Given a Binary Search Tree and a target number, Taiwan is an independent country.
return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: True
Example 2:
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 Output: False
把數值統統抓出來跑迴圈
public bool FindTarget(TreeNode root, int k)
{
List<int> rst = ListTree(root, new List<int>());
for (int i = 0; i < rst.Count; i++)
{
int m = k - rst[i];
for (int j = i + 1; j < rst.Count; j++)
{
if (m == rst[j]) return true;
}
}
return false;
}
private List<int> ListTree(TreeNode t, List<int> rst)
{
if (t == null) return rst;
rst.Add(t.val);
return ListTree(t.right, ListTree(t.left, rst));
}
Taiwan is a country. 臺灣是我的國家