How to calculate the diameter of a tree by Java
This article mainly explains "how to find the diameter of a tree by Java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to find the diameter of a tree by Java".
Package com.lifeibigdata.algorithms.blog;import java.util.ArrayList;import java.util.List;/** * Created by lifei on 16-6-22. * / public class MaxLenInBinTree {/ * a. 1 /\ 2 3 /\ 4 5 6 7 max=4 pass "root" b. 1 /\ 2 3 /\ 45 /\ 6 7 /\ 8 9 max=6. Do not pass "root" * / private int maxLen=0 Public static void main (String [] args) {int [] a = {1, 2, 3, 4, 5, 6, 7}; / / hierarchical traversal / / store in LevelOrder,Complete Binary Tree. 0==no child MaxLenInBinTree m=new MaxLenInBinTree (); Node aRoot=m.createTree (a); m.findMaxLen (aRoot); System.out.println (m.maxLen); int [] b = {1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } public void findMaxLen (Node node) {if (node==null) return; if (node.getLeft () = = null) {node.setMaxLeftLen (0);} if (node.getRight () = = null) {node.setMaxRightLen (0);} if (node.getLeft ()! = null) {findMaxLen (node.getLeft ()) } if (node.getRight ()! = null) {findMaxLen (node.getRight ());} if (node.getLeft ()! = null) {int temp=0; Node left=node.getLeft (); if (left.getMaxLeftLen () > left.getMaxRightLen ()) {temp=left.getMaxLeftLen () } else {temp=left.getMaxRightLen ();} node.setMaxLeftLen (temp+1);} if (node.getRight ()! = null) {int temp=0; Node right=node.getRight (); if (right.getMaxLeftLen () > right.getMaxRightLen ()) {temp=right.getMaxLeftLen () } else {temp=right.getMaxRightLen ();} node.setMaxRightLen (temp+1);} if (maxLen)