剑指Offer—38—二叉树的深度

来源:互联网 发布:linux ext3 ext4 区别 编辑:程序博客网 时间:2024/06/08 07:03

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

package A38二叉树的最大深度;import java.util.LinkedList;import java.util.Queue;public class Demo {    public int TreeDepth(TreeNode pRoot){        if (pRoot == null){            return 0;        }        Queue<TreeNode> queue = new LinkedList<>();        queue.add(pRoot);        int depth = 0;        while (!queue.isEmpty()){            depth++;            int size = queue.size();            while (size-- > 0){                TreeNode temp = queue.poll();                if (temp.left != null){                    queue.add(temp.left);                }                if (temp.right != null){                    queue.add(temp.right);                }            }        }        return depth;    }}
package A38二叉树的最大深度;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;        }        int left = TreeDepth(root.left);        int right = TreeDepth(root.right);        return (left > right) ? (left + 1) : (right + 1);    }}
package A38二叉树的最大深度;import java.util.LinkedList;import java.util.Queue;public class Solution1 {    // 层次遍历    public int TreeDepth(TreeNode pRoot){        if (pRoot == null){            return 0;        }        Queue<TreeNode> queue = new LinkedList<>();        queue.add(pRoot);        int depth = 0;        while (!queue.isEmpty()){            int len = queue.size();            depth++;            while (len-- > 0) {  // 把队列中的元素吐完                TreeNode top = queue.poll();                if (top.left != null) {                    queue.add(top.left);                }                if (top.right != null) {                    queue.add(top.right);                }            }        }        return depth;    }}
原创粉丝点击