【資料結構】演算法 Maximum Width of Binary Tree 二叉樹最大寬度
阿新 • • 發佈:2021-06-23
目錄
Maximum Width of Binary Tree 二叉樹最大寬度
二叉樹的寬度:
每一層的寬度被定義為兩個端點(該層最左和最右的非空節點,兩端點間的null節點也計入長度)之間的長度。
輸入:A = [3,4,5,1,2], B = [4,1] 輸出:true輸入: 1 / \ 3 2 / \ \ 5 3 9 輸出: 4 解釋: 最大值出現在樹的第 3 層,寬度為 4 (5,3,null,9)。
思路
利用層序遍歷的方式,記錄節點和序號。
將每層的最右節點序號r - 最左節點的序號l。
遞迴
public class TwoTuple<A,B> { public final A first; public final B second; public TwoTuple(A a, B b){ first = a; second = b; } } public int widthOfBinaryTree(TreeNode root) { LinkedList<TwoTuple<TreeNode, Integer>> q = new LinkedList<>(); q.offer(new TwoTuple<>(root,0)); int ans = 0; while (!q.isEmpty()){ int cnt = q.size(); int l = q.peekFirst().second; int r=0; for (int i = 0; i < cnt; i++) { TwoTuple<TreeNode, Integer> temp = q.peek(); r = temp.second -l; if(temp.first.left!=null){ q.offer(new TwoTuple<>(temp.first.left,r*2)); } if(temp.first.right!=null){ q.offer(new TwoTuple<>(temp.first.right,r*2+1)); } q.poll(); } ans = Math.max(ans,r+1); } return ans; }
Tag
tree