leetcode_102_Binary Tree Level Order Traversal

來源:互聯網
上載者:User

標籤:binary tree   level order traversa   

1.描述

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ‘s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.

Here‘s an example:

   1  /  2   3    /   4         5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
2.思路

一般的層序遍曆直接列印出結果,用隊列即可,但是此次的要求尼是按層次列印結果,所以考慮到用兩個隊列來交替儲存,遍曆上一層次的同時將下一層的結點儲存到另一個隊列中,並在將上面一層的遍曆完成後交換兩個隊列的值。

3.代碼
/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> levelOrder(TreeNode root) {       List<List<Integer>>list=new ArrayList<List<Integer>>();//儲存結果       if(root==null)       return list;       Queue<TreeNode>q1=new LinkedList<TreeNode>();//交替儲存相鄰兩層的結點       Queue<TreeNode>q2=new LinkedList<TreeNode>();       Queue<TreeNode>temp=null;       List<Integer>subList=null;//儲存一層的結點的值       q1.add(root);       TreeNode top=null;       while(!q1.isEmpty())       {       subList=new ArrayList<Integer>();       while(!q1.isEmpty())//迴圈遍曆一層結點並將下一層結點儲存到隊列中       {       top=q1.peek();       q1.poll();       if(top.left!=null)       q2.add(top.left);       if(top.right!=null)       q2.add(top.right);       subList.add(top.val);       }       list.add(subList);       temp=q2;//交換兩個隊列的值,使q1一直指向要遍曆的那一層       q2=q1;       q1=temp;       }       return list;}}


4.結果

leetcode_102_Binary Tree Level Order Traversal

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.