This is a common operation on a two-fork tree. To summarize:
Set the data structure of the node as follows:
1 class TreeNode { 2 char Val; 3 TreeNode left = null ; 4 TreeNode right = ; 5 char _val) { 7 this . val = _val; 8 9 }
1. Two Fork Tree Depth
This can be used recursively, to find out the depth of the Zuozi, the depth of the right subtree, two depth of a larger value of +1.
1 //Get maximum depth2 Public Static intgetmaxdepth (TreeNode root) {3 if(Root = =NULL)4 return0;5 Else {6 intleft =getmaxdepth (root.left);7 intright =getmaxdepth (root.right);8 return1 +Math.max (left, right);9 }Ten}
2. Two Fork tree width
Using queues, the hierarchy traverses the binary tree. after the previous traversal is complete, all nodes in the next layer are placed in the queue, and the number of elements in the queue is the width of the next layer. then, the maximum width of a two-fork tree can be calculated by traversing the next layer in turn.
1 //Get maximum width2 Public Static intgetmaxwidth (TreeNode root) {3 if(Root = =NULL)4 return0;5 6queue<treenode> queue =NewArraydeque<treenode>();7 intMaxwitdth = 1;//Maximum width8Queue.add (root);//Queue9 Ten while(true) { One intLen = Queue.size ();//the number of nodes in the current layer A if(len = = 0) - Break; - while(Len > 0) {//if the current layer, there are also nodes theTreeNode T =Queue.poll (); -len--; - if(T.left! =NULL) -Queue.add (T.left);//queue the next layer of nodes + if(T.right! =NULL) -Queue.add (T.right);//queue the next layer of nodes + } AMaxwitdth =Math.max (Maxwitdth, Queue.size ()); at } - returnMaxwitdth; -}
Reference: http://blog.csdn.net/htyurencaotang/article/details/12406223
Finding the depth and width of a binary tree [Java]