算法要求:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
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 17 } 18 }
思路:
1.若根节点是空节点,则为空树,深度为0;
2.若根节点不为空,则选择左子树和右子树中深度大的为新树,原树的深度是新树的深度+1;
3.递归
解题过程:
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 == null){ //判断是否是空树 17 return 0; 18 } 19 int cLeft = TreeDepth(root.left); //左子树的深度 20 int cRight = TreeDepth(root.right); //右子树的深度 21 return Math.max(cLeft,cRight)+1; 22 } 23 }