1. 程式人生 > >劍指offer程式設計題(JAVA實現)——第38題:二叉樹的深度

劍指offer程式設計題(JAVA實現)——第38題:二叉樹的深度



github https://github.com/JasonZhangCauc/JZOffer
  • 劍指offer程式設計題(JAVA實現)——第38題:二叉樹的深度
  • 題目描述
  • 輸入一棵二叉樹,求該樹的深度。
  • 從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。
public class Test38 {

	public static void main(String[] args) {
		
		

	}

	public
int TreeDepth(TreeNode root) { return depth(root,0); } private int depth(TreeNode root, int i) { if (root == null) { return 0; } i = i + 1; TreeNode tmp = root; int left = 0; int right = 0; if (tmp.left != null) { left = depth(tmp.left, i); } if (tmp.right != null) {
right = depth(tmp.right, i); } return Math.max(i, Math.max(left, right)); } public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } } //其他方法 /** public class Solution { public int TreeDepth(TreeNode root) { if(root==null){ return 0; } int nLelt=TreeDepth(root.left); int nRight=TreeDepth(root.right); return nLelt>nRight?(nLelt+1):(nRight+1); } } */