請實作一個函式按照之字形列印二叉樹,即第一行按照從左到右的順序列印,第二層按照從右至左的順序列印,第三行按照從左到右的順序列印,其他行以此類推,
分析:https://blog.csdn.net/qq_40608516/article/details/91128825
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function Print(pRoot) { // write code here const lists=[] if(pRoot===null){ return lists } const stack1=[],stack2=[] let i=1 stack2.push(pRoot) while(stack1.length!==0||stack2.length!==0){ const list=[] //為奇數層 if((i % 2) === 1){ while(stack2.length!==0){ const temp=stack2[stack2.length-1] stack2.pop() list.push(temp.val) if(temp.left!==null)stack1.push(temp.left) if(temp.right!==null)stack1.push(temp.right) } }else{ while(stack1.length!=0){ const temp=stack1[stack1.length-1] stack1.pop() list.push(temp.val) if(temp.right!==null)stack2.push(temp.right) if(temp.left!==null)stack2.push(temp.left) } } i++ lists.push(list) } return lists }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/24673.html
標籤:其他
上一篇:樹---對稱的二叉樹
下一篇:樹---把二叉樹列印成多行
