java计算二叉树的节点最小值_java计算二叉树的高度以及叶节点个数
java實(shí)現(xiàn)二叉樹(shù)的相關(guān)操作
代碼如下
package 二叉樹(shù)有關(guān); import java.util.ArrayDeque; import java.util.Queue; public class CreateTree { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Node root=new Node(); root.data=9; Node temp01=new Node(); temp01.data=1; root.left=temp01; Node temp02=new Node(); temp02.data=3; root.right=temp02; Node temp03=new Node(); temp03.data=2; root.left.left=temp03; Node temp04=new Node(); temp04.data=4; root.left.right=temp04; Node temp05=new Node(); temp05.data=8; root.right.left=temp05; Node temp06=new Node(); temp06.data=6; root.left.left.left=temp06; Node temp07=new Node(); temp07.data=7; root.left.left.right=temp07; System.out.println("--------先序遍歷----------"); SelectTree1(root); System.out.println(); System.out.println("---------中序遍歷---------"); SelectTree(root); System.out.println(); System.out.println("---------后序遍歷---------"); SelectTree2(root); System.out.println(); System.out.println("----------葉節(jié)點(diǎn)個(gè)數(shù)-----------"); int i=leafNum(root); System.out.println(i); System.out.println("----------層次遍歷二叉樹(shù)-----------------"); levelOrder(root); System.out.println(); int j=deep(root); System.out.println("---------高度---------"); System.out.println(j); } // 中序遍歷 public static void SelectTree(Node root){ if(root==null) return; SelectTree(root.left); System.out.print(root.data+" "); SelectTree(root.right); } // 先序遍歷 public static void SelectTree1(Node root){ if(root==null) return; System.out.print(root.data+" "); SelectTree1(root.left); SelectTree1(root.right); } // 后序遍歷 public static void SelectTree2(Node root){ if(root==null) return; SelectTree2(root.left); SelectTree2(root.right); System.out.print(root.data+" "); } // 葉子數(shù) public static int leafNum(Node node) {? ? ? ? ?if (node != null) {? ? ? ? ? ? ?if (node.left == null && node.right == null) {? ? ? ? ? ? ? ? ?return 1;? ? ? ? ? ? ?}? ? ? ? ? ? ?return leafNum(node.left)+leafNum(node.right);? ? ? ? ?}? ? ? ? ?return 0;? ? ?}? ? //求二叉樹(shù)的深度? ? ?public static int deep(Node node){? ? ? int h1, h2; ? ? ? ?if(node == null)? ? ? ? ? {return 0;? ? ? ? ? } ? ? ? ?else{ ? ?h1= deep(node.left); ? ?h2= deep(node.right); ? ? ?return (h1
queue = new ArrayDeque();? ? ? ? ?queue.add(node);? ? ? ? ?while (!queue.isEmpty()) {? ? ? ? ? Node temp = queue.poll();? ? ? ? ? ? ?System.out.print(temp.data);? ? ? ? ? ? ?if (temp.left != null)? ? ? ? ? ? ? ? ?queue.add(temp.left);? ? ? ? ? ? ?if (temp.right != null)? ? ? ? ? ? ? ? ?queue.add(temp.right);? ? ? ? ?}? ? ?}? } class Node{ boolean visited=false; int data=0; Node left=null; Node right=null; }
總結(jié)
以上是生活随笔為你收集整理的java计算二叉树的节点最小值_java计算二叉树的高度以及叶节点个数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: c++ 字符串数组长度排序_数组 | 后
- 下一篇: 俄罗斯机器人雄鹿_在雄鹿无球可打,在火箭
