leetcode- 二叉樹的層次遍歷(binary tree level order traversal)-java
阿新 • • 發佈:2018-12-11
題目及測試
package pid102; import java.util.List; /*二叉樹的層次遍歷 給定一個二叉樹,返回其按層次遍歷的節點值。 (即逐層地,從左到右訪問所有節點)。 例如: 給定二叉樹: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其層次遍歷結果: [ [3], [9,20], [15,7] ] }*/ public class main { public static void main(String[] args) { Object[] x=new Object[]{1,2,2,3,4,4,3}; BinaryTree tree=new BinaryTree(x); tree.printTree(tree.root); test(tree.root); Object[] x2=new Object[]{3,9,20,null,null,15,7}; BinaryTree tree2=new BinaryTree(x2); tree2.printTree(tree2.root); test(tree2.root); } private static void test(TreeNode ito) { Solution solution = new Solution(); List<List<Integer>> rtn; long begin = System.currentTimeMillis(); rtn = solution.levelOrder(ito);//執行程式 long end = System.currentTimeMillis(); System.out.println("rtn=" ); for (List<Integer> list : rtn) { for (Integer integer : list) { System.out.print(integer+" "); } System.out.println(); } System.out.println(); System.out.println("耗時:" + (end - begin) + "ms"); System.out.println("-------------------"); } }
解法1(成功,2ms,很快) 建立一個queue,一個rowlist, 一個現在層次的節點數num,一個下一層next 將root加入queue 當queue不為空 從queue取出頭,num–,將值加入rowlist,將left,right加入queue尾部,next++ 當num為0 則num=next,next=0,結果加入rowlist,rowlist新建一個
package pid102; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result=new ArrayList<List<Integer>>(); List<Integer> rowResult=new ArrayList<Integer>(); if(root==null){ return result; } int num=1; int next=0; Queue<TreeNode> queue=new LinkedList<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { TreeNode now=queue.poll(); rowResult.add(now.val); num--; if(now.left!=null){ queue.add(now.left); next++; } if(now.right!=null){ queue.add(now.right); next++; } if(num==0){ num=next; next=0; result.add(rowResult); rowResult=new ArrayList<Integer>(); } } return result; } }