要素の最大合計を持つバイナリ ツリーでレベルを見つけるためのコードを作成しました。いくつかの質問を聞きたいんです。
- 良いデザインですか?- 2 つのキューを使用しましたが、両方のキューに格納される要素の総数は n 未満になります。だから大丈夫だと思います。
より良いデザインはありますか?
public class MaxSumLevel { public static int findLevel(BinaryTreeNode root) { Queue mainQ = new Queue(); Queue tempQ = new Queue(); int maxlevel = 0; int maxVal = 0; int tempSum = 0; int tempLevel = 0; if (root != null) { mainQ.enqueue(root); maxlevel = 1; tempLevel = 1; maxVal = root.getData(); } while ( !mainQ.isEmpty()) { BinaryTreeNode head = (BinaryTreeNode) mainQ.dequeue(); BinaryTreeNode left = head.getLeft(); BinaryTreeNode right = head.getRight(); if (left != null) { tempQ.enqueue(left); tempSum = tempSum + left.getData(); } if (right != null) { tempQ.enqueue(right); tempSum = tempSum + right.getData(); } if (mainQ.isEmpty()) { mainQ = tempQ; tempQ = new Queue(); tempLevel ++; if (tempSum > maxVal) { maxVal = tempSum; maxlevel = tempLevel; tempSum = 0; } } } return maxlevel; }
}