剑指offer:二叉树的深度

来源:互联网 发布:c51单片机的最小系统图 编辑:程序博客网 时间:2024/05/29 18:21

题目描述

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

递归

运行时间:14ms  占用内存:8272k
public class Solution {    public int TreeDepth(TreeNode root) {        if(root==null)  return 0;        int right=TreeDepth(root.right);        int left =TreeDepth(root.left);        return (right>left)?(right+1):(left+1);    }}

非递归

【运行时间:15ms  占用内存:8244k】

利用广度优先遍历方式来找二叉树的层数,即为二叉树的高度

/**public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/import java.util.*;public class Solution {    public int TreeDepth(TreeNode root) {        if(root==null)return 0;        LinkedList<TreeNode> queue=new LinkedList<TreeNode>();        queue.offer(root);        int depth=0;        while(!queue.isEmpty()){            int size=queue.size();            for(int i=0;i<size;i++){                TreeNode cur=queue.poll();                if(cur.left!=null)                    queue.offer(cur.left);                if(cur.right!=null)                    queue.offer(cur.right);            }            depth++;        }        return depth;    }}



原创粉丝点击