Welcome to Subscribe On Youtube

Question

Formatted question description: https://leetcode.ca/all/1214.html

 Given two binary search trees,
 return True if and only if
    there is a node in the first tree and a node in the second tree whose values sum up to a given integer target.


 Example 1:
   2     1
  / \   / \
 1   4 0   3

 Input: root1 = [2,1,4], root2 = [1,0,3], target = 5
 Output: true
 Explanation: 2 and 3 sum up to 5.

 @tag-array

Algorithm

Get two ordered list, and 2 pointers to move forward for each.

Code

  • import java.util.ArrayList;
    import java.util.List;
    
    
    public class Two_Sum_BSTs {
    
        // Time: O(M+N)
        // Space: O(logmax(M,N)) in the best case; O(max(M,N)) in the worst case.
        public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {
    
            // Convert to list
            List<Integer> list1 = new ArrayList<>();
            List<Integer> list2 = new ArrayList<>();
            listByInorder(root1, list1);
            listByInorder(root2, list2);
    
            // Two Pointers
            int lo = 0, hi = list2.size() - 1;
            while (lo < list1.size() && hi >= 0) { // notice the condition here
                int sum = list1.get(lo) + list2.get(hi);
                if (sum == target) {
                    return true;
                } else if (sum < target) {
                    ++lo;
                } else {
                    --hi;
                }
            }
            return false;
        }
    
        private void listByInorder(TreeNode root, List<Integer> list) {
            if (root == null) {
                return;
            }
            listByInorder(root.left, list);
            list.add(root.val);
            listByInorder(root.right, list);
        }
    }
    
    ############
    
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {
            List<Integer> vals1 = new ArrayList<>();
            List<Integer> vals2 = new ArrayList<>();
            inorder(root1, vals1);
            inorder(root2, vals2);
            int i = 0, j = vals2.size() - 1;
            while (i < vals1.size() && j >= 0) {
                int s = vals1.get(i) + vals2.get(j);
                if (s == target) {
                    return true;
                }
                if (s < target) {
                    ++i;
                } else {
                    --j;
                }
            }
            return false;
        }
    
        private void inorder(TreeNode root, List<Integer> vals) {
            if (root != null) {
                inorder(root.left, vals);
                vals.add(root.val);
                inorder(root.right, vals);
            }
        }
    }
    
  • // OJ: https://leetcode.com/problems/two-sum-bsts/
    // Time: O(A + B)
    // Space: O(HA + HB)
    class Solution {
        void pushNodes(stack<TreeNode*> &s, TreeNode *n, bool right = false) {
            for (; n; n = right ? n->right : n->left) s.push(n);
        }
    public:
        bool twoSumBSTs(TreeNode* a, TreeNode* b, int target) {
            stack<TreeNode*> sa, sb;
            pushNodes(sa, a);
            pushNodes(sb, b, true);
            while (sa.size() && sb.size()) {
                int sum = sa.top()->val + sb.top()->val;
                if (sum == target) return true;
                if (sum < target) {
                    auto n = sa.top();
                    sa.pop();
                    pushNodes(sa, n->right);
                } else {
                    auto n = sb.top();
                    sb.pop();
                    pushNodes(sb, n->left, true);
                }
            }
            return false;
        }
    };
    
  • # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool:
            vals1, vals2 = [], []
    
            def inorder(root, vals):
                if root:
                    inorder(root.left, vals)
                    vals.append(root.val)
                    inorder(root.right, vals)
    
            inorder(root1, vals1)
            inorder(root2, vals2)
    
            i, j = 0, len(vals2) - 1
            while i < len(vals1) and j >= 0:
                if vals1[i] + vals2[j] == target:
                    return True
                if vals1[i] + vals2[j] < target:
                    i += 1
                else:
                    j -= 1
            return False
    
    
    
  • /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    func twoSumBSTs(root1 *TreeNode, root2 *TreeNode, target int) bool {
    	vals1 := inorder(root1)
    	vals2 := inorder(root2)
    	i, j := 0, len(vals2)-1
    	for i < len(vals1) && j >= 0 {
    		s := vals1[i] + vals2[j]
    		if s == target {
    			return true
    		}
    		if s < target {
    			i++
    		} else {
    			j--
    		}
    	}
    	return false
    }
    
    func inorder(root *TreeNode) []int {
    	if root == nil {
    		return nil
    	}
    	left := inorder(root.Left)
    	right := inorder(root.Right)
    	return append(append(left, root.Val), right...)
    }
    

All Problems

All Solutions