LeetCode 653: Two Sum IV - Input is a BST
2017-09-01 14:26
375 查看
Edge case:
need to determine whether two numbers come from same node.
need to determine whether two numbers come from same node.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean findTarget(TreeNode root, int k) { if (root == null) { return false; } return inorderAndSearch(root, root, k); } private boolean inorderAndSearch(TreeNode current, TreeNode root, int target) { if (current == null) { return false; } return inorderAndSearch(current.left, root, target) || findValue(root, target - current.val, current) || inorderAndSearch(current.right, root, target); } private boolean findValue(TreeNode root, int value, TreeNode current) { if (root == null) { return false; } return (root != current && root.val == value) || findValue(root.left, value, current) || findValue(root.right, value, current); } }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean findTarget(TreeNode root, int k) { if (root == null) { return false; } List<Integer> nums = new ArrayList<>(); inorder(root, nums); int start = 0; int end = nums.size() - 1; while (start < end) { if (nums.get(start) + nums.get(end) == k) { return true; } else if (nums.get(start) + nums.get(end) > k) { end--;; } else { start++;; } } return false; } private void inorder(TreeNode root, List<Integer> nums) { if (root == null) { return; } inorder(root.left, nums); nums.add(root.val); inorder(root.right, nums); } }
相关文章推荐
- leetcode 653 Two Sum IV - Input is a BST
- LeetCode之Two Sum IV - Input is a BST(Kotlin)
- LeetCode Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST(leetcode)
- 算法分析与设计——LeetCode Problem.653 Two Sum IV - Input is a BST
- [LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
- leetcode[Two Sum IV - Input is a BST]//待整理多种解法
- leetcode Two Sum IV - Input is a BST 两个数的和
- LeetCode Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST
- LeetCode #653 Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST
- LeetCode.653 Two Sum IV - Input is a BST
- LC-Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST问题及解法
- [Leetcode]Two Sum II - Input array is sorted
- leetcode Two Sum II - Input array is sorted 两个数的和
- [leetcode] 1. twoSum; 167. Two Sum II - Input array is sorted; 15. threeSum; 16. 3Sum Closest; 18. 4