算法_求二叉树的深度

package com.btm.util;

 

public class Node {

private String name;

private Node leftN;

private Node rightN;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Node getLeftN() {

return leftN;

}

public void setLeftN(Node leftN) {

this.leftN = leftN;

}

public Node getRightN() {

return rightN;

}

public void setRightN(Node rightN) {

this.rightN = rightN;

}

public Node(String name) {

this.name = name;

}

@Override

public String toString() {

return name;

}

}

package com.btm.util;

 

public class BinaryTree {

private Node root;

public BinaryTree() {

root = null;

}

public Node getRoot() {

return root;

}

public void setRoot(Node root) {

this.root = root;

}

public void initTree() {

Node node1 = new Node("a");

Node node2 = new Node("b");

Node node3 = new Node("c");

Node node4 = new Node("d");

Node node5 = new Node("e");

root = node1;

node1.setLeftN(node2);

node2.setRightN(node3);

node1.setRightN(node4);

node3.setLeftN(node5);

}

int length(Node root) {

int depth1;

int depth2;

if (root == null)

return 0;

depth1 = length(root.getRightN());

 

depth2 = length(root.getLeftN());

if (depth1 > depth2)

return depth1 + 1;

else

return depth2 + 1;

}

}

public static void main(String[] args) {

    BinaryTree tree = new BinaryTree();

    tree.initTree();

    System.out.println(tree.length(tree.getRoot()));

    }

你可能感兴趣的:(算法_求二叉树的深度)