面试题39:二叉树的深度

来源:互联网 发布:javascript招聘工资 编辑:程序博客网 时间:2024/05/17 09:12

二叉树深度

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

求二叉树的深度,有三种方法: 
1. 递归,这也是很多人非常容易想到的,递归实际也是深度优先的思想(DFS),时间复杂度为O(lgN),但是空间复杂度最坏为O(N),当二叉树退化为链表的时候。 
2. 循环,这种方法不会有递归方法容易出现的栈溢出风险。循环其实是广度优先的思想(BFS)。时间复杂度O(N)


递归

分析:如果该树只有一个结点,它的深度为1.如果根节点只有左子树没有右子树,那么树的深度为左子树的深度加1;同样,如果只有右子树没有左子树,那么树的深度为右子树的深度加1。如果既有左子树也有右子树,那该树的深度就是左子树和右子树的最大值加1. 
这个思路用递归实现如下:

  public int getTreeDepth(TreeNode root) {        if (root == null) {            return 0;        }        return Math.max(getTreeDepth(root.left), getTreeDepth(root.right)) + 1;    }

循环

上述递归也可以改为循环:

import java.util.LinkedList;import java.util.Queue;public class Solution {    public int TreeDepth(TreeNode root) {        if (root == null) {            return 0;        }      // return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;                Queue<TreeNode> queue = new LinkedList<>();        queue.offer(root);        int count = 0, depth = 0, nextCount = 1;        while (!queue.isEmpty()) {            TreeNode node = queue.poll();//删除元素第一个元素(head)            count ++;            if (node.left != null) {                queue.offer(node.left);// offer方法在添加元素时,如果发现队列已满无法添加的话,会直接返回false。            }            if (node.right != null) {                queue.offer(node.right);            }            if (count == nextCount) {                nextCount = queue.size();                count = 0;                depth++;            }        }        return depth;    }}

判断该树是不是平衡二叉树

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

首先,什么是平衡二叉树?如果二叉树中任意结点的左右子树深度相差不超过1,那么它就是平衡二叉树。

递归法

有了求二叉树的深度的经验之后,很容易想到一个思路:遍历每个结点的时候,得到它的左右结点的深度。如果每个结点的左右二叉树的深度相差都不超过1,就是平衡二叉树。

public class Solution {    public boolean IsBalanced_Solution(TreeNode root) {        if(root==null)            return true;               int left=depth(root.left);        int right=depth(root.right);        if(Math.abs(left-right)>1)            return false;                 return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);    }     public int depth(TreeNode root){        if(root==null)            return 0;        int left=depth(root.left);        int right=depth(root.right);        return (left>right)?(left+1):(right+1);    }}



但是这个方法每个结点被重复遍历,效率不高。

自底向上

另一个思路: 
如果我们用后序遍历的方式遍历二叉树的每一个结点,在遍历到一个结点之前我们就已经遍历了它的左右子树。只要在遍历每个结点的时候几下它的深度,就可以一次遍历判断每个结点是不是平衡二叉树。

public class Solution {    private boolean isBalanced=true;    public boolean IsBalanced_Solution(TreeNode root) {        getTreeDepth(root);        return isBalanced;    }    public int getTreeDepth(TreeNode root){        if(root==null)            return 0;        int left=getTreeDepth(root.left);        int right=getTreeDepth(root.right);        if(Math.abs(left-right)>1)            isBalanced=false;        return Math.max(left,right)+1;    }}






原创粉丝点击