java寬度優先將二叉樹存成數組
阿新 • • 發佈:2017-07-17
元素 max imp tree list() style 排列 順序 源碼
題目:
有一棵二叉樹,請設計一個算法,按照層次打印這棵二叉樹。給定二叉樹的根結點root,
請返回打印結果,結果按照每一層一個數組進行儲存,所有數組的順序按照層數從上往下,且每一層的數組內元素按照從左往右排列。保證結點數小於等於500。
解題思路:
類似上一篇文章中的思路
源碼:
package ss.entity; public class TreeNode { int val; TreeNode left; TreeNode right; public int getVal() { return val; } publicvoid setVal(int val) { this.val = val; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) {this.right = right; } public TreeNode(int x) { val = x; } public boolean equals(Object obj) { return super.equals(obj); } }
package ss.tree; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import ss.entity.TreeNode;/** * 有一棵二叉樹,請設計一個算法,按照層次打印這棵二叉樹。 * 給定二叉樹的根結點root, * 請返回打印結果, * 結果按照每一層一個數組進行儲存, * 所有數組的順序按照層數從上往下, * 且每一層的數組內元素按照從左往右排列。保證結點數小於等於500。 * */ public class TreeDemo03 { public static void main(String[] args){ TreeNode tree = new TreeNode(1); tree.setLeft(new TreeNode(2)); tree.setRight(new TreeNode(3)); tree.getLeft().setLeft(new TreeNode(4)); tree.getRight().setLeft(new TreeNode(5)); tree.getRight().setRight(new TreeNode(6)); tree.getRight().getLeft().setLeft(new TreeNode(7)); tree.getRight().getLeft().setRight(new TreeNode(8)); int[][] a = TreeDemo03.printTree(tree); for(int[] b : a){ for(int c : b){ System.out.print(c); } System.out.println(); } } public static int[][] printTree(TreeNode root) { TreeNode last = root; TreeNode nlast = null; Queue queue = new LinkedList(); queue.add(root); List<List> list = new ArrayList<List>(); List<Integer> temp = new ArrayList<Integer>(); int maxWidth = 0; while(!queue.isEmpty()){ TreeNode tempNode = (TreeNode)queue.poll(); temp.add(tempNode.getVal()); if(null != tempNode.getLeft()){ queue.add(tempNode.getLeft()); nlast = tempNode.getLeft(); } if(null != tempNode.getRight()){ queue.add(tempNode.getRight()); nlast = tempNode.getRight(); } if(tempNode.equals(last)){ last = nlast; list.add(temp); if(temp.size() > maxWidth) maxWidth = temp.size(); temp = new ArrayList<Integer>(); }else{ continue; } } int[][] result = new int[list.size()][maxWidth]; for(int i = 0; i < list.size(); i++){ List<Integer> ll = list.get(i); for(int j = 0; j < list.get(i).size(); j++){ result[i][j] = ll.get(j); } } return result; } }
java寬度優先將二叉樹存成數組