[二叉樹的層序遍歷(Leetcode 102)
阿新 • • 發佈:2020-10-29
二叉樹的層序遍歷(Leetcode 102)
資料結構定義:
// Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
演算法:
//每次遍歷都是一層資料 //定義一個佇列,佇列初始的大小就是一層的資料大小 //每次迴圈都從頭拿資料,並將子樹放入佇列中 class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); LinkedList<TreeNode> queue =new LinkedList<>(); if(root == null){ return result; } queue.add(root); while(!queue.isEmpty()){ int size = queue.size(); List<Integer> temp =new ArrayList<>(); for(int i =0;i<size;i++){ TreeNode node =queue.removeFirst(); temp.add(node.val); if(node.left != null){ queue.add(node.left); } if(node.right != null){ queue.add(node.right); } } result.add(temp); } return result; } }