1st round, 314 binaryTreeVerticalTraversal

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root==null) return result;
        
        Queue<TreeNode> nodeQ = new LinkedList<>();  // have a clear idea of what nodeQ contains.
        Queue<Integer> levelQ = new LinkedList<>();  // have a clear idea of what levelQ contains.
        Map<Integer, List<Integer>> map = new HashMap<>(); // have a clear idea of what map contains.
        
        nodeQ.add(root);
        levelQ.add(0);
        
        int min=0;
        int max=0;
        
        while(!nodeQ.isEmpty()){   // while(nodeQ!=null) is wrong!! should check whether it is empty.
            TreeNode node=nodeQ.poll();
            int level=levelQ.poll();
            
            if(!map.containsKey(level)) map.put(level, new ArrayList<Integer>());
            map.get(level).add(node.val); // have a clear idea of what map contains.
            
            if(node.left!=null){
                nodeQ.add(node.left);
                levelQ.add(level-1);
                min=Math.min(min, level-1);
            }
            
            if(node.right!=null){
                nodeQ.add(node.right);
                levelQ.add(level+1);
                max=Math.max(max, level+1);
            }
            // for the above two if() statements only if we have some in either left or right child, we add the child to the Q, otherwise need to do nothing.
        }
        
        for(int i=min; i<=max; i++){
            result.add(map.get(i));
        }
        return result;
    }
}

        // have no idea about the question in the beginning, but after looking through solutions I immediately get the idea, it is the BFS approach. Did I know BFS?? Of course!!! You did many quesitons on BFS, basically it is reading elems on same level of tree, and then move to the next level.
        // here there are many things for me to 总结, such as using Queue<> (Interface) and LinkedList<>(class) to track the information on each level. ALSO, understanding this question and transfering it to some simple questions and easy solutions is a good practice. Lastly, knowing using min, max to keep record of the range is the key point to this question!! 一会好好总结在ppt上。。
        


这道题,虽然代码略多,但是思路还是非常清晰简练的。。。相信读者看代码就能知道我什么意思。。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值