算法_求二叉树的深度


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()));

    }

本站声明
本文转载自:http://katy1206.iteye.com/blog/2148391     作者:maomide_fannao     发布日期:2014-10-27     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2016 ITdaan.com 粤ICP备14056181号