これは、バイナリツリーの一般的な操作です。まとめ:
次のように、ノードのデータ構造を設定しましょう。
次のようにコードコードをコピーします。
class treeNode {
char値;
treenode left = null;
treenode right = null;
treeNode(char _val){
this.val = _val;
}
}
1。バイナリツリーの深さ
これを復活させることができ、左サブツリーの深さが見つかり、右の子供の木の深さを使用できます。
次のようにコードコードをコピーします。
//最大の深さを取得します
public static int getMaxDepth(treeNode root){{{
if(root == null)
0を返します。
それ以外 {
int left = getMaxDepth(root.left);
int right = getMaxDepth(root.richt);
1 + math.max(左、右)を返します。
}
}
2。バイナリ幅
キューを使用して、バイナリツリー層を通過します。前のレイヤーが完了した後、次のレイヤーのすべてのノードがキューに配置されました。類推により、次のレイヤーにバイナリツリーの最大幅を見つけることができます。
次のようにコードコードをコピーします。
//最大幅を取得します
public static int getMaxWidth(Timeode root){{
if(root == null)
0を返します。
キュー<tar
int maxwitdth = 1; //
queue.add(root);
while(true){
int len = queue.size();
if(len == 0)
壊す;
while(len> 0){//現在のレイヤーの場合、ノードがあります
t = queue.poll()を扱います。
len-;
if(t.left!= null)
Queue.Add(T.Left);
if(t.right!= null)
queue.add(t.right); //次のノード
}
maxwitdth = math.max(maxwitdth、queue.size());
}
maxwitdthを返します。
}