binary-tree-level-order-traversal

/**
* Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
* For example:
* Given binary tree{3,9,20,#,#,15,7},
* 3
* / \
* 9 20
* / \
* 15 7
* return its level order traversal as:
* [
* [3],
* [9,20],
* [15,7]
* ]
*/
这道题目,主要是我们是否知道树的层次遍历。
/**
 * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
 * For example:
 * Given binary tree{3,9,20,#,#,15,7},
 *      3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * return its level order traversal as:
 * [
 *   [3],
 *   [9,20],
 *   [15,7]
 * ]
 */

import java.util.ArrayList;

public class Main37 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(Main37.levelOrder(root));
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode (int x){
            val = x;
        }
    }

    public static ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        ArrayList<TreeNode> treeNodes = new ArrayList<>();

        if (root == null) {
            return list;
        }
        TreeNode head = null;
        treeNodes.add(root);
        while(!treeNodes.isEmpty()) {
            ArrayList<Integer> array = new ArrayList<>();
            ArrayList<TreeNode> newTree = new ArrayList<>();
            for (int i=0;i<treeNodes.size();i++) {
                head = treeNodes.get(i);
                array.add(head.val);
                if (head.left != null) {
                    newTree.add(head.left);
                }
                if (head.right != null) {
                    newTree.add(head.right);
                }
            }
            treeNodes = newTree;
            list.add(array);
        }
        return list;
    }
}
参考资料:https://blog.csdn.net/snow_7/article/details/51815787

转载于:https://www.cnblogs.com/strive-19970713/p/11315628.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值