码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Level Order Traversal

时间:2015-03-28 11:34:43      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

问题来源:https://leetcode.com/problems/binary-tree-level-order-traversal/

package cn.edu.shu;

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

/**
 * 
 * <p>
 * ClassName BinaryTreeLevelOrderTraversal
 * </p>
 * <p>
 * Description 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] ]
 * </p>
 * 
 * @author TKPad wangx89@126.com
 *         <p>
 *         Date 2015年3月27日 下午10:53:07
 *         </p>
 * @version V1.0.0
 *
 */
public class BinaryTreeLevelOrderTraversal {
    List<List<Integer>> results = new ArrayList<List<Integer>>();
    List<Integer> list = new ArrayList<Integer>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<List<Integer>>();
        }
        breadthFirstSearch(root);
        return results;
    }

    // 我的主要思路就是在每一层的最后一个节点后面加一个标记“null”,这样当读取到null的时候,就知道一层结束了,需要加入集合
    public void breadthFirstSearch(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        queue.add(null);
        TreeNode tn = null;
        while (!(queue.size() == 1 && null == tn)) {
            tn = queue.remove();
            if (null == tn) {
                queue.add(null);// 作为一个标记
                // 说明一层遍历完了
                List<Integer> temp = new ArrayList<Integer>(list);
                results.add(temp);
                list.clear();
                continue;
            }
            list.add(tn.val);
            if (tn.left != null) {
                queue.add(tn.left);
            }
            if (tn.right != null) {
                queue.add(tn.right);
            }
        }

    }

    public static void main(String[] args) {
        TreeNode tn1 = new TreeNode(5);
        TreeNode tn2 = new TreeNode(4);
        TreeNode tn3 = new TreeNode(8);
        TreeNode tn4 = new TreeNode(11);
        TreeNode tn5 = new TreeNode(13);
        TreeNode tn6 = new TreeNode(4);
        TreeNode tn7 = new TreeNode(7);
        tn1.left = tn2;
        tn2.left = tn3;
        tn3.left = tn4;
        // tn1.right = tn5;
        // tn1.right = tn3;
        // tn2.left = tn4;
        // tn2.right = tn5;
        // tn4.left = tn6;
        // tn4.right = tn7;
        // tn2.left = tn3;

        List<List<Integer>> levelOrder = new BinaryTreeLevelOrderTraversal().levelOrder(tn1);
        System.out.println(levelOrder);
    }
}

Binary Tree Level Order Traversal

标签:

原文地址:http://blog.csdn.net/shijiebei2009/article/details/44699841

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!