触点数字孪生,揭秘它的独特魅力
588
2022-10-12
Write a function to find the depth of a binary tree
class BinaryTree { static class Node { char data; Node left=null; Node right=null; int i; } public static char[] dataArray = new char[] { 'a', 'b', 'c','d','e' ,'f','g','h','i','j','k','l','m','n','o'}; public static Node creatRoot(Node node) { if (node.i < dataArray.length) { if (node.data == '-') node = null; if (node != null) node.data = dataArray[node.i]; node.left = creatLeft(node); node.right = creatRight(node); } return node; } public static Node creatLeft(Node node) { if (node != null) { node.left = new Node(); node.left.i = 2 * node.i + 1; creatRoot(node.left); } return node.left; } public static Node creatRight(Node node) { if (node != null) { node.right = new Node(); node.right.i = 2 * node.i + 2; creatRoot(node.right); } return node.right; } public static void preOrder(Node node) { if (node != null) { System.out.print(node.data + " "); preOrder(node.left); preOrder(node.right); } } public static void inOrder(Node node) { if (node != null) { inOrder(node.left); System.out.print(node.data + " "); inOrder(node.right); } } public static void postOrder(Node node) { if (node != null) { postOrder(node.left); postOrder(node.right); System.out.print(node.data + " "); } } public static void main(String args[]) { Node node = new Node(); node = creatRoot(node); preOrder(node); System.out.println(); inOrder(node); System.out.println(); postOrder(node); System.out.println(); System.out.print(depth(node)-1); } public static int depth(Node node) { int lDepth,rDepth; if(node==null){ return 0; } lDepth=depth(node.left); rDepth=depth(node.right); return (lDepth>rDepth?lDepth:rDepth)+1; }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。