剑指offer--二叉树的深度

来源:互联网 发布:windows 2008 server 编辑:程序博客网 时间:2024/06/05 03:18

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

分类:二叉树

解法1:递归
[java] view plain copy
  1. /** 
  2. public class TreeNode { 
  3.     int val = 0; 
  4.     TreeNode left = null; 
  5.     TreeNode right = null; 
  6.  
  7.     public TreeNode(int val) { 
  8.         this.val = val; 
  9.  
  10.     } 
  11.  
  12. } 
  13. */  
  14. public class Solution {  
  15.     public int TreeDepth(TreeNode root) {  
  16.         if(root==nullreturn 0;  
  17.         if(root.left==null&&root.right==nullreturn 1;  
  18.         int left = TreeDepth(root.left);  
  19.         int right = TreeDepth(root.right);  
  20.         return left>right?left+1:right+1;  
  21.     }  


原文链接  http://blog.csdn.net/crazy__chen/article/details/45013007