Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to calculate the diameter of a tree by Java

Shulou Source: shulou.com Published: 2022-05-31 17:56:51 10月04日 Update

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)

Tags: Diameter content learning practical deeper interested practical practical hierarchical easy to operate method more friends websites channels a. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Huawei Shulou Tech Info Docker Shulou Technology