107. Binary Tree Level Order Traversal II

原题链接:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
这道题目是 http://www.cnblogs.com/optor/p/8538693.html 这一道的后续,也是很简单。
那就故技重施,最后把结果反转下就行啦哈哈哈😁:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);

        TreeNode rootLeft = new TreeNode(2);
        TreeNode rootRight = new TreeNode(3);
        root.left = rootLeft;
        root.right = rootRight;

        TreeNode leftLeft = new TreeNode(3);
        TreeNode leftRight = null;
        rootLeft.left = leftLeft;
        rootLeft.right = leftRight;

        TreeNode rightLeft = new TreeNode(2);
        TreeNode rightRight = null;
        rootRight.left = rightLeft;
        rootRight.right = rightRight;

        Solution s = new Solution();
        System.out.println(s.levelOrderBottom(root));
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        dfs(queue, res);

        List<List<Integer>> res2 = new ArrayList<>();
        for (int i = res.size() - 1; i >= 0; i--) {
            res2.add(res.get(i));
        }
        return res2;
    }

    public void dfs(Queue<TreeNode> parentQueue, List<List<Integer>> res) {
        Queue<TreeNode> childQueue = new LinkedList<>();

        List<Integer> parentVals = new ArrayList<>();
        while (!parentQueue.isEmpty()) {
            TreeNode node = parentQueue.poll();
            parentVals.add(node.val);

            if (node.left != null) {
                childQueue.add(node.left);
            }
            if (node.right != null) {
                childQueue.add(node.right);
            }
        }
        res.add(parentVals);
        if (childQueue.size() > 0) {
            dfs(childQueue, res);
        }
    }
}
posted @ 2018-03-10 12:14  optor  阅读(124)  评论(0编辑  收藏  举报