1. 程式人生 > >二叉樹層次遍歷列印

二叉樹層次遍歷列印

二叉樹層次遍歷列印,並且每層對應輸出換行(遍歷一層輸出後,下一層遍歷換行輸出)。

final static int MAX_NUM = 500
class TreeNode {  //二叉樹結構
	    int val = 0;
	    TreeNode left = null;
	    TreeNode right = null;
	    public TreeNode(int val) {
	        this.val = val;
	    }
	}
	//層次遍歷
	    public int[][] printTree(TreeNode root) {
	        int shuzu[][] = new int[MAX_NUM/2][MAX_NUM/2];
	        int last = 0;//nlast = 0;
	        int i=0,j=0;
	        int head=0,tail=0;
	        TreeNode[] q = new TreeNode[MAX_NUM];
	        TreeNode p;
	        if(root!=null){
	            tail = (tail+1)%MAX_NUM;
	            q[tail] = root;
	            last = root.val;
	        }
	        while(head!=tail){
	            head = (head+1)%MAX_NUM;
	            p = q[head];
	            if(p.val == last){
	                shuzu[i][j] = p.val;
	                i++;
	                j=0;
	            }
	            else{
	              shuzu[i][j] = p.val;
	              j++;
	            }
	            if(root.left!=null){
	                tail = (tail+1)%MAX_NUM;
	                q[tail] = root.left;
	            }
	                
	            if(root.right!=null){
	                tail = (tail+1)%MAX_NUM;
	                q[tail] = root.right;
	                //nlast = q[tail].val;
	                last = q[tail].val;
	            }
	                
	        }
	        return shuzu;
	    }