vlambda博客
学习文章列表

数据结构与算法-求给定二叉树的最大深度

题目描述:   

    求给定二叉树的最大深度,最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。


解题思路:

    1. 递归法;

    2. 迭代算法:借助队列。


实现代码:

import java.util.LinkedList;
public class BinaryTreeMaxDdepth { /** * * @param root TreeNode类 * @return int整型 */ public static int maxDepth (TreeNode root) { return maxDepthByIterator(root); } /** * 迭代算法 * @param root TreeNode类 * @return int整型 */ public static int maxDepthByIterator (TreeNode root) { // write code here if(root==null){ return 0; } if(root.left==null&& root.right==null){ return 1; }
LinkedList<TreeNode> list = new LinkedList<TreeNode>(); list.push(root); int maxDepth = 0; while(!list.isEmpty()){ int levelSize = list.size(); while (levelSize>0){ TreeNode cur = list.pollLast(); --levelSize; if (cur.left!=null){ list.push(cur.left); } if (cur.right!=null){ list.push(cur.right); } } maxDepth++; } return maxDepth; }

/** * 递归算法 * @param root TreeNode类 * @return int整型 */ public static int maxDepthByRecruit (TreeNode root) { // write code here if(root==null){ return 0; } if(root.left==null&& root.right==null){ return 1; } int leftMaxDepth = maxDepthByRecruit(root.left)+1; int rightMaxDepth = maxDepthByRecruit(root.right)+1; return Math.max(leftMaxDepth,rightMaxDepth); }
public static void main(String[] args){ //{1,2,3,4,#,#,5} TreeNode root = new TreeNode(1,new TreeNode(2,new TreeNode(4,null,null),null),new TreeNode(3,null,new TreeNode(5,null,null))); int max = maxDepth(root); System.out.println(max); }}
class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val,TreeNode left,TreeNode right){ this.val = val; this.left = left; this.right = right; } }