Java实现二叉树的深度

来源:互联网 发布:tough cookie.js 编辑:程序博客网 时间:2024/06/11 01:05

题目描述

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

我的第一版代码:想着用递归,哎....WRONG!

/**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) {        int re=1;        int i=1,j=1;        boolean flag=true;        while(flag){            if(root.left!=null){                i++;                root=root.left;            }else if(root.right!=null){                j++;                root=root.right;            }else{                                flag=false;            }            re=i>=j?i:j;                                }        return re;    }}


看了一下大神的代码:

链接:https://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b来源:牛客网import java.lang.Math;public class Solution {    public int TreeDepth(TreeNode pRoot)    {        if(pRoot == null){            return 0;        }        int left = TreeDepth(pRoot.left);        int right = TreeDepth(pRoot.right);        return Math.max(left, right) + 1;    }}


然后用非递归的方法做,也可以

链接:https://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b来源:牛客网public class Solution {    public int TreeDepth(TreeNode pRoot)    {        if(pRoot == null){            return 0;        }        Queue<TreeNode> queue = new LinkedList<TreeNode>();        queue.add(pRoot);        int depth = 0, count = 0, nextCount = 1;        while(queue.size()!=0){            TreeNode top = queue.poll();            count++;            if(top.left != null){                queue.add(top.left);            }            if(top.right != null){                queue.add(top.right);            }            if(count == nextCount){                nextCount = queue.size();                count = 0;                depth++;            }        }        return depth;    }}

说是非常巧妙了: