Loading

107. 二叉树的层次遍历 II

107. 二叉树的层次遍历 II

https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/description/

package com.test;

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

/**
 * @Author stono
 * @Date 2018/8/27 上午10:40
 */
public class Lesson107 {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(1);
        TreeNode t2L = new TreeNode(2);
        TreeNode t2R = new TreeNode(2);
        TreeNode t3_1 = new TreeNode(3);
        TreeNode t3_2 = new TreeNode(4);
        TreeNode t3_3 = new TreeNode(4);
        TreeNode t3_4 = new TreeNode(3);
        t1.left = t2L;
        t1.right = t2R;
        t2L.left = t3_1;
        t2L.right = t3_2;
        t2R.left = t3_3;
        t2R.right = t3_4;
        List<List<Integer>> lists = levelOrderBottom(t1);
        System.out.println(lists);
    }
    public static List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        List<Integer> list = new ArrayList<>(8);
        list.add(root.val);
        TreeNode leftNode = root.left;
        TreeNode rightNode = root.right;
        List<TreeNode> nodes = new ArrayList<>();
        nodes.add(leftNode);
        nodes.add(rightNode);
        // 进行递归累加
        levelOrderBottom(res, nodes);
        res.add(list);
        return res;
    }

    private static void levelOrderBottom(List<List<Integer>> res, List<TreeNode> nodes) {
        List<Integer> list = new ArrayList<>(8);
        List<TreeNode> nodes2 = new ArrayList<>();
        for (TreeNode node : nodes) {
            if (node != null) {
                list.add(node.val);
                nodes2.add(node.left);
                nodes2.add(node.right);
            }
        }
        // 如果遍历结果中包含了多个数字
        if (list.size() > 0) {
            levelOrderBottom(res, nodes2);
            res.add(list);
        }
    }
}

 

posted @ 2018-08-27 11:11  stono  阅读(146)  评论(0编辑  收藏  举报