剑指Offer面试题55:二叉树的深度

题目一

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

解题思路:

解题代码:

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        //二叉树问题一般递归遍历操作实现
        if(pRoot==nullptr)         //递归终止条件
            return 0;
        int LeftTreeDepth = TreeDepth(pRoot->left); //递归求左子树深度
        int RightTreeDepth= TreeDepth(pRoot->right);//递归求右子树深度
        return max(LeftTreeDepth,RightTreeDepth)+1;
    }
};

 题目二

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

解题思路:

        首先明白平衡二叉树的概念:1 它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1

                                                            2 并且左右两个子树都是一棵平衡二叉树。

解题代码:

解法一,利用TreeDepth函数求解,但此种方法会有大量重复计算,重复遍历节点。

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot==nullptr)
            return true;
        int left =TreeDepth(pRoot->left);
        int right=TreeDepth(pRoot->right);
        int diff=left-right;
        if(diff>1 || diff<-1)
            return false;
        return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
    }
private:
    int TreeDepth(TreeNode* pRoot)
    {
        //二叉树问题一般递归遍历操作实现
        if(pRoot==nullptr)         //递归终止条件
            return 0;
        int LeftTreeDepth = TreeDepth(pRoot->left); //递归求左子树深度
        int RightTreeDepth= TreeDepth(pRoot->right);//递归求右子树深度
        return max(LeftTreeDepth,RightTreeDepth)+1;
    }
};

解法二,更好的解法

 用后序遍历的方式遍历二叉树的每个节点,那么在遍历到每一个节点之前我们就已经遍历了他的左、右子树。只要在遍历每个节点的时候记录他的深度,我们就可以一边遍历一边判断每个节点是不是平衡的。

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth=0;
        return IsBalanced(pRoot,&depth);
    }
private:
    bool IsBalanced(TreeNode* pRoot,int* pDepth)  //深度depth是变量,但是depth的地址,即指向depth的指针不会变
    {
        if(pRoot==nullptr)
        {
            *pDepth=0;
            return true;
        }
        int left,right;
        if(IsBalanced(pRoot->left,&left)&&IsBalanced(pRoot->right,&right))
        {
            int diff=left-right;
            if(diff<=1 && diff>=-1)
            {
                *pDepth=1+(left>right ? left:right);
                return true;
            }
        }
        return false;
    }
};

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值