Leetcode之路3:Binary Tree Traversal、Two Sum

Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},
1

2
/
3
return [3,2,1].

简单的题...直接上代码

package binary.tree.postorder.traversal;

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

/*
 * 二叉树的后续遍历 
 * 没有要求的话就用递归,应该很快
 * 如果他的左子叶为空,则访问其右子叶,右子叶为空,访问上级点
 * 如果其右子叶不为空,则递归进入
 */
public class Solution {
    
    private List result;
    
    public Solution(){
        result = new ArrayList();
    }
    public List postorderTraversal(TreeNode root) {
        postorderTraversal2(root);
        return result;        
    }
    
    public void postorderTraversal2(TreeNode root){
        if(root == null)
            return ;    
        if(root.left != null){
            postorderTraversal2(root.left);
        }
        if(root.right != null){
            postorderTraversal2(root.right);
        }
        result.add(root.val);
    }
}

Binary Tree Preorder Traversal 也很简单,实现了上面的这个也不难 不上代码了

算法课上肯定会学的...凭印象自己实现了一下

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Output: index1=1, index2=2



输入一个数组,找到 满足两数之和等于目标数的下标,返回

/*

  • 最简单思路 扫描 超时了
    */
    public class Solution {
    public int[] twoSum(int[] numbers, int target) {
    int[] result = {0,0};
    for(int count1 = 0;count1 < numbers.length ; count1++){
    for(int count2 = count1;count2 < numbers.length;count2++){
    if(count1 == count2)
    continue;
    if(numbers[count1] + numbers[count2] == target){
    result[0] = count1;
    result[1] = count2;
    return result;
    }
    }
    }

     return null;
    

    }
    }


出现的问题在于要多次扫描  那么使用HashMap减少扫描

public class Solution {
int[] result = { 0 , 0 };
public int[] twoSum(int[] numbers, int target) {
Map temp = new HashMap();
for(int i = 0;i < numbers.length ; i++){
temp.put( target - numbers[i] , i);
}

    for(int i = 0;i < numbers.length ; i++){
        if(temp.containsKey(numbers[i])){
            if(i == temp.get(numbers[i])){
                continue;
            }else if(i > temp.get(numbers[i])){
                result[0] = temp.get(numbers[i]);
                result[1]  = i;
                return result;
            }else if(i < temp.get(numbers[i])){
                result[0] = i;
                result[1]  = temp.get(numbers[i]);
                return result;
            }
        }
    }
    return null;
}

public static void main(String[] args){
    Solution test = new Solution();
    int[] temp = {3,2,4};
    System.out.println(test.twoSum( temp, 6));
}

}


恩恩 通过...



你可能感兴趣的:(Leetcode之路3:Binary Tree Traversal、Two Sum)