This is a common operation to binary tree. Summary:
Let's set the data structure of the node, as follows:
Copy code code as follows:
Class Treenode {
char value;
Treenode left = null;
Treenode right = null;
Treenode (char _Val) {
this.val = _Val;
}
}
1. Binary tree depth
This can be recubled, and the depth of the left subtree is found, and the depth of the right child tree can be used.
Copy code code as follows:
// Get the maximum depth
Public Static Int GetmaxDepth (Treenode Root) {{
if (root == null)
Return 0;
else {
int left = getmaxDepth (root.left);
int Right = getmaxdepth (root.richt);
Return 1 + math.max (left, right);
}
}
2. Binary width
Use the queue to traverse the binary tree layer. After the previous layer is completed, all nodes in the next layer have been placed in the queue. At this time, the number of elements in the queue is the width of the next layer. By analogy, you can find the maximum width of the binary tree in the next layer.
Copy code code as follows:
// Get the maximum width
public static int Getmaxwidth (timeode root) {{
if (root == null)
Return 0;
Queue <tar
int maxwitdth = 1; // maximum width
queue.add (root); // join the team
While (true) {
int len = queue.size (); // The number of nodes of the current layer
if (len == 0)
Break;
While (len> 0) {// If the current layer, there are nodes
Treat t = queue.poll ();
len-;
if (t.Left! = NULL)
queue.add (t.Left); // Next node to the team
if (T.right! = Null)
queue.add (T.Right); // Next node to the team
}
maxwitdth = math.max (maxwitdth, queue.size ());
}
Return maxwitdth;
}