剑指offer系列(38)二叉树的深度

题目描述

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


思路分析

先复习一下概念

树的深度:以二叉树的根结点所在的层数为1,根结点的孩子结点所在的层数为2,以此下去。深度是指所有结点中最深的结点所在的层数。

递归思路:树的深度为左右子树深度的较大值+1,以此递归到底层,即可得出答案

循环思路:借鉴之前打印二叉树的思路,层序遍历,设置一变量,记录遍历的层数。


代码

递归

//递归
	public int TreeDepth(TreeNode root) {
		if (root == null) {
			return 0;
		}
		int left = TreeDepth(root.left);
		int right = TreeDepth(root.right);
		return Math.max(left, right)+1;
	}
	
	public class TreeNode {
	    int val = 0;
	    TreeNode left = null;
	    TreeNode right = null;
	    
	    public TreeNode(int val) {
	        this.val = val;
	    }
	}

结果



循环

//循环
	public int TreeDepth(TreeNode root) {
        if (root == null){
        	return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        queue.offer(root);
        int start = 0;  //当前层数已添加节点数
        int end = 1;   //当前层数目标添加节点数
        int count = 0;  //记录层数
        while (!queue.isEmpty()){
        	TreeNode temp = queue.poll(); 
        	list1.add(temp.val);
        	start++;
        	if (temp.left != null) {
				queue.offer(temp.left);
			}
        	if (temp.right != null) {
				queue.offer(temp.right);
			}
        	if (start == end) {
				end = queue.size(); //本层的所有节点已出队,队列中所剩刚好是下一层的全部节点
				start = 0;
				list1 = new ArrayList<Integer>();
				count++;
			}
        }
        return count;    		
    }
结果



猜你喜欢

转载自blog.csdn.net/sun10081/article/details/80725769