剑指offer:输入一棵二叉树,求该树的深度。

题目描述:

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

分析:假设已知一棵二叉树的左子树和右子树的深度,怎么算出整棵树的深度呢?

        这是问题的关键。如果有一棵二叉树,左子树的深度为left,右子树的深度为right,则整棵树的深度就是max(left,right)+ 1,即左右子树中的最大值加上1。

        这正对应于先序遍历左子树(得到左子树的深度left),再遍历右子树(得到右子树的深度right),最后访问根(得到整棵树的深度为max(left,right)+ 1)的后序遍历方式。

    /**
    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;
            else
            {
                int left = TreeDepth(root.left);
                int right = TreeDepth(root.right);
                /*if (left >= right)
                    return left + 1;
                else
                    return right + 1;*/
                return Math.max(left, right)+1;
            }
        }
    }

方法二:宽度遍历

运用二叉树的宽度遍历(Breadth First Search),二叉树的宽度遍历是用(first-in,first-out)的队列来实现。

        要进行宽度遍历,建立一个队列。先将二叉树的头节点1入队列,然后出队列。访问1节点,如果它有左子树,则将左子树的根节点2入队列;如果它有右子树,则将右子树的根节2点入队列。然后2、3节点出队列。同理访问2、3节点的左右子树。。。

        用nextCount记录下一层的节点数,当count的值等于nextCount时,说明当前层的节点已经全部访问完毕,深度+1。

    /**
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
            this.val = val;
        }
    }
    */
    import java.util.LinkedList;
    import java.util.Queue;
    public class Solution {
        public int TreeDepth(TreeNode root) {
            if(root == null)
            {
                return 0;
            }
            Queue<TreeNode> queue = new LinkedList<TreeNode>();//构造方法,构建一个空列表
            int depth = 0,count = 0,nextCount = 1;//分别定义二叉树的深度,已经遍历的结点数,和下一层结点的总数
            queue.add(root);//将指定元素添加到此列表的结尾
            while(queue.size() != 0)//检查列表的元素个数
            {
                TreeNode temp = queue.poll();//获取并移除此列表的头(第一个元素)
                count += 1;//每移出一个元素,就加1。
                if(temp.left != null)
                {
                    queue.add(temp.left);
                }
                if(temp.right != null)
                {
                    queue.add(temp.right);
                }
                if(count == nextCount)
                {
                    depth += 1;
                    count = 0;//将count清零
                    nextCount = queue.size();//nextCount是下一层的结点总数
                }
            }
            return depth;
        }
    }

 
---------------------
版权声明:本文为CSDN博主「wanqian_2019」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_28632639/article/details/88087614

posted @ 2019-08-06 15:31  天涯海角路  阅读(393)  评论(0)    收藏  举报