最大高度
function getMaxHeight(root){ if(root == null) return 0; return 1 + Math.max(getMaxHeight(root.left),getMaxHeight(root.right)); }
最小高度
function getMinHeigth(root){ if(!root) return 0; return 1 + Math.min(getMinHeight(root.left),getMinHeight(root.right)); }
二叉樹寬度
遞歸方法
function getMaxWidth(root){ if(root == null) return 0; if(root.left == null && root.right == null) return 1; return getMaxWidth(root.left) + getMaxWdith(root.right); }
非遞歸方法求二叉樹的高度和寬度
//使用層次遍歷,求最大高度和最大寬度 function getMaxSize(root){ let queue = [root]; let width = 0; let height = 0; while(queue.length){ let levelSize = queue.length; width = Math.max(levelSize,width); height++; while(levelSize--){ let node = queue.shift(); if(node.left) queue.push(node.left); if(node.right) queue.push(node.right); } } return [width,height]; }
還有一種在每行末尾添加null的方式,雖然不及上面的簡潔,但是思路值得肯定
function bfs(root){ if(!root) return; //第一行先在末尾加個null let queue = [root,null]; let deep = 0; //rows可以記錄每行的寬度 let rows = []; while(queue.length){ let node = queue.shift(); //為null表示本行結束 if(node == null){ deep++; //本行結束,下一行的node已經push完畢,在此處加null,就是在下一行的末尾加null //queue的長度若為0,則說明最后一行,無需再加null if(queue.length) queue.push(null); } else{ rows[deep] = ~~rows[deep] + 1; if(node.left) queue.push(node.left); if(node.right) queue.push(node.right); } } return deep; }