給定一個二叉樹,返回其按層次遍歷的節點值。 (即逐層地,從左到右訪問所有節點)。
例如:
給定二叉樹: [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其層次遍歷結果:
[ [3], [9,20], [15,7] ]
借鑒其他人的思路,采用廣度優先探索,使用隊列。
若根節點為空,直接返回;
若根節點非空,則將根節點入隊,然后,判斷隊列是否為空,若不為空,則將隊首節點出隊,訪問,並判斷其左右子節點是否為空,若不為空,則壓入隊列。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { List<List<Integer>> res=new ArrayList(); public List<List<Integer>> levelOrder(TreeNode root) { if(root==null)return res; //邊界條件 Queue<TreeNode> q=new LinkedList(); //創建的隊列用來存放結點,泛型注意是TreeNode q.add(root); while(!q.isEmpty()){ //隊列為空說明已經遍歷完所有元素,while語句用於循環每一個層次 int count=q.size(); List<Integer> list=new ArrayList(); while(count>0){ //遍歷當前層次的每一個結點,每一層次的Count代表了當前層次的結點數目 TreeNode temp=q.peek(); q.poll(); //遍歷的每一個結點都需要將其彈出 list.add(temp.val); if(temp.left!=null)q.add(temp.left); //迭代操作,向左探索 if(temp.right!=null)q.add(temp.right); count--; } res.add(list); } return res; } }