剑指offer 学习笔记 二叉树的深度

面试题55:二叉树的深度。
1.输入一棵二叉树,求该树的深度。

只需遍历整棵树的每一条路径找出最长的即可,以下代码中的树结构为:
在这里插入图片描述

#include <iostream>
using namespace std;

struct BinaryTreeNode {
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};

BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder) {    // 创建树
    BinaryTreeNode* root = new BinaryTreeNode();
    root->m_nValue = *startPreorder;
    root->m_pLeft = root->m_pRight = nullptr;

    if (startPreorder == endPreorder) {    // 当递归到前序遍历只含一个元素时
        if (startInorder == endInorder && *startPreorder == *startInorder) {    // 此时若中序遍历也只含一个元素并且这个元素值与前序遍历的元素值相同时,递归到底成功返回
            return root;
        } else {    // 否则当前序和中序遍历的个数不相等(前序遍历只含一个元素但中序遍历有多个元素)或值不相等(前序遍历和中序遍历元素数都为1但这两个值不等)时
            throw exception("Invalid input.");    // 说明输入的前序和中序遍历不匹配
        }
    }

    int* rootInorder = startInorder;
    while (rootInorder < endInorder && *rootInorder != *startPreorder) {    // 遍历中序序列找到根节点
        ++rootInorder;
    }

    if (rootInorder == endInorder && *rootInorder != *startPreorder) {    // 若以上循环结束仍未找到根节点,说明输入有误
        throw exception("Invalid input");
    }

    int leftLength = rootInorder - startInorder;    // 左子树长度
    int* leftPreorderEnd = startPreorder + leftLength;    // 左子树先序遍历尾边界
    if (leftLength > 0) {    // 当左子树仍存在时
        root->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1);    // 继续递归左子树
    }
    if (leftLength < endPreorder - startPreorder) {    // 左子树长度小于当前遍历的树节点数-1(去掉根节点)时,说明存在右子树
        root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder);    // 继续递归右子树
    }

    return root;
}

BinaryTreeNode* Construct(int* preorder, int* inorder, int length) {    // 创建树
    if (preorder == nullptr || inorder == nullptr || length <= 0) {
        return nullptr;
    }

    return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1);
}

int TreeDepth(BinaryTreeNode* pRoot) {
    if (pRoot == nullptr) {
        return 0;
    }
    
    int leftDepth = TreeDepth(pRoot->m_pLeft);
    int rightDepth = TreeDepth(pRoot->m_pRight);

    return max(leftDepth, rightDepth) + 1;
}

int main() {
    int preorder[] = { 1,2,4,5,7,3,6 };
    int inorder[] = { 4,2,7,5,1,3,6 };
    BinaryTreeNode* pRoot = Construct(preorder, inorder, sizeof(preorder) / sizeof(*preorder));
    cout << "树的深度为:" << TreeDepth(pRoot) << endl;
}

2.输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左、右子树的深度相差不超过1,那么它就是一棵平衡二叉树,上例的树就是一棵平衡二叉树。

我们可以根据题目1来求解,遍历树的每个节点,遍历到每个节点时调用获取树的深度的函数来获取节点的两个子树的深度:

bool IsBalanced(BinaryTreeNode* pRoot) {
    if (pRoot == nullptr) {
        return true;
    }

    int leftDepth = TreeDepth(pRoot->m_pLeft);
    int rightDepth = TreeDepth(pRoot->m_pRight);
    if (leftDepth - rightDepth > 1 || leftDepth - rightDepth < -1) {
        return false;
    }

    return IsBalanced(pRoot->m_pLeft) && IsBalanced(pRoot->m_pRight);
}

但以上方法一个节点会被遍历多次,太慢了。我们可以通过后序遍历来实现每个节点只遍历一次,即从下向上地计算结果:

#include <iostream>
using namespace std;

struct BinaryTreeNode {
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};

BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder) {    // 创建树
    BinaryTreeNode* root = new BinaryTreeNode();
    root->m_nValue = *startPreorder;
    root->m_pLeft = root->m_pRight = nullptr;

    if (startPreorder == endPreorder) {    // 当递归到前序遍历只含一个元素时
        if (startInorder == endInorder && *startPreorder == *startInorder) {    // 此时若中序遍历也只含一个元素并且这个元素值与前序遍历的元素值相同时,递归到底成功返回
            return root;
        } else {    // 否则当前序和中序遍历的个数不相等(前序遍历只含一个元素但中序遍历有多个元素)或值不相等(前序遍历和中序遍历元素数都为1但这两个值不等)时
            throw exception("Invalid input.");    // 说明输入的前序和中序遍历不匹配
        }
    }

    int* rootInorder = startInorder;
    while (rootInorder < endInorder && *rootInorder != *startPreorder) {    // 遍历中序序列找到根节点
        ++rootInorder;
    }

    if (rootInorder == endInorder && *rootInorder != *startPreorder) {    // 若以上循环结束仍未找到根节点,说明输入有误
        throw exception("Invalid input");
    }

    int leftLength = rootInorder - startInorder;    // 左子树长度
    int* leftPreorderEnd = startPreorder + leftLength;    // 左子树先序遍历尾边界
    if (leftLength > 0) {    // 当左子树仍存在时
        root->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1);    // 继续递归左子树
    }
    if (leftLength < endPreorder - startPreorder) {    // 左子树长度小于当前遍历的树节点数-1(去掉根节点)时,说明存在右子树
        root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder);    // 继续递归右子树
    }

    return root;
}

BinaryTreeNode* Construct(int* preorder, int* inorder, int length) {    // 创建树
    if (preorder == nullptr || inorder == nullptr || length <= 0) {
        return nullptr;
    }

    return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1);
}

bool IsBalanced(BinaryTreeNode* pRoot, int& depth) {
    if (pRoot == nullptr) {
        depth = 0;
        return true;
    }

    int leftDepth = 0, rightDepth = 0;
    if (IsBalanced(pRoot->m_pLeft, leftDepth) && IsBalanced(pRoot->m_pRight, rightDepth)) {
        if (leftDepth - rightDepth <= 1 && rightDepth - leftDepth >= -1) {
            depth = max(leftDepth, rightDepth) + 1;
            return true;
        }
    }
    return false;
}

bool IsBalanced(BinaryTreeNode* pRoot) {
    int depth = 0;
    return IsBalanced(pRoot, depth);
}

int main() {
    int preorder[] = { 1,2,4,5,7,3,6 };
    int inorder[] = { 4,2,7,5,1,3,6 };
    BinaryTreeNode* pRoot = Construct(preorder, inorder, sizeof(preorder) / sizeof(*preorder));
    cout << (IsBalanced(pRoot) ? "是一棵平衡二叉树" : "不是平衡二叉树") << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值