标签:
【题目】输入一棵二叉树,求该树的深度。
* 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
1 package com.exe9.offer; 2 3 /** 4 * 【题目】输入一棵二叉树,求该树的深度。 5 * 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 6 * @author WGS 7 * 8 */ 9 public class BTreeDepth { 10 11 static class TreeNode{ 12 int val; 13 TreeNode left=null; 14 TreeNode right=null; 15 public TreeNode(int val){ 16 this.val=val; 17 } 18 } 19 20 public int getBTreeDepth(TreeNode pRoot){ 21 if(pRoot==null) return 0; 22 //每当proot==null时,就比较left与right大小,加1 23 int left=getBTreeDepth(pRoot.left); 24 int right=getBTreeDepth(pRoot.right); 25 //System.out.println(left+"===="+right); 26 return (left>right)?left+1:right+1; 27 28 } 29 public static void main(String[] args) { 30 TreeNode root = new TreeNode(1); 31 TreeNode node1 = new TreeNode(2); 32 TreeNode node2 = new TreeNode(3); 33 TreeNode node3 = new TreeNode(4); 34 TreeNode node4 = new TreeNode(5); 35 TreeNode node5 = new TreeNode(6); 36 TreeNode node6 = new TreeNode(7); 37 38 root.left = node1; 39 root.right = node2; 40 node1.left = node3; 41 node1.right = node4; 42 node2.right = node5; 43 node4.left = node6; 44 45 int d=new BTreeDepth().getBTreeDepth(root); 46 System.out.println(d); 47 48 49 } 50 51 }
标签:
原文地址:http://www.cnblogs.com/noaman/p/5604995.html