Binary Tree Level Order Traversal

问题来源: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;

/**
 * 
 * 

* ClassName BinaryTreeLevelOrderTraversal *

*

* 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] ] *

* * @author TKPad [email protected] *

* Date 2015年3月27日 下午10:53:07 *

* @version V1.0.0 * */
public class BinaryTreeLevelOrderTraversal { List> results = new ArrayList>(); List list = new ArrayList(); public List> levelOrder(TreeNode root) { if (root == null) { return new ArrayList>(); } breadthFirstSearch(root); return results; } // 我的主要思路就是在每一层的最后一个节点后面加一个标记“null”,这样当读取到null的时候,就知道一层结束了,需要加入集合 public void breadthFirstSearch(TreeNode root) { Queue queue = new LinkedList(); 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 temp = new ArrayList(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> levelOrder = new BinaryTreeLevelOrderTraversal().levelOrder(tn1); System.out.println(levelOrder); } }

你可能感兴趣的:(LeetCode,OJ)