Two Sum - BST edtion

http://www.lintcode.com/en/problem/two-sum-bst-edtion/?rand=true

package com.LintCode.TwoSumBSTedtion;

import com.LintCode.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Definition of TreeNode:
 * public class TreeNode {
 * public int val;
 * public TreeNode left, right;
 * public TreeNode(int val) {
 * this.val = val;
 * this.left = this.right = null;
 * }
 * }
 */

public class Solution {

    /*
     * @param : the root of tree
     * @param : the target sum
     * @return: two numbers from tree which sum is n
     */
    public int[] twoSum(TreeNode root, int n) {
        // write your code here
//        先中序遍历得到所有的值
        List list = new ArrayList<>();
        tree(root, list);
        int i = 0;
        int j = list.size() - 1;
        while (i < j) {
//            再找两个数的和
            int sum = list.get(i) + list.get(j);
            if (sum > n) {
                j--;
            } else if (sum < n) {
                i++;
            } else {
                return new int[]{list.get(i), list.get(j)};
            }
        }
        return null;
    }

    private void tree(TreeNode root, List list) {
        if (root == null) {
            return;
        }
        tree(root.left, list);
        list.add(root.val);
        tree(root.right, list);
    }
}

你可能感兴趣的:(Two Sum - BST edtion)