The sword refers to Offer - interview question 39: the depth of the binary tree (how to judge whether a binary tree is a balanced binary tree)

Find the depth of a binary tree


Question: Enter the root node of a binary tree and find the depth of the tree. The nodes (including the root and leaf nodes) that pass through in sequence from the root node to the leaf node form a path of the tree, and the length of the longest path is the depth of the tree. For example, the depth of the binary tree in the figure below is 4, because its longest path from the root node to the leaf node contains 4 nodes (starting from root node 1, going through node 2 and node 5, and finally reaching the leaf node Node 7).

Input: binary tree as shown below

write picture description here

Output: The depth of the binary tree is 4

Ideas: 1. Using the idea of ​​recursion, for each node, determine the depth of its left subtree, and determine the depth of its right subtree
. 2. Take the depth of the left subtree and the maximum depth of the left subtree +1, It is the depth
Ps of the node: expressed by the formula: max[ (leftLen+1), (rightLen+1) ]

/*
实现:求二叉树深度的函数TreeDepth
*/
int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot==NULL){
            return 0;
        }
        int leftLen = TreeDepth(pRoot->left);
        int rightLen= TreeDepth(pRoot->right);
        return leftLen>rightLen ? (leftLen+1) : (rightLen+1);
    }

Determine whether it is a balanced binary tree


/*
实现:判断是否是平衡二叉树
*/
//简单版,但是存在不足,就是会遍历很多重复的节点
bool IsBalanced(BinaryTreeNode* pRoot){
    if (pRoot == NULL){
        return true;
    }
    int leftLen = TreeDepth(pRoot->left);
    int rightLen = TreeDepth(pRoot->right);
    int diff = leftLen - rightLen;
    if (diff > 1 || diff < -1){
        return false;
    }
    return IsBalanced(pRoot->left) && IsBalanced(pRoot->right);
}

//利用后序遍历,这样对每个节点只需要遍历一次
bool IsBalanced(BinaryTreeNode* pRoot,int* depth){
    if (pRoot == NULL){
        *depth = 0;
        return true;
    }
    if (IsBalanced(pRoot->left, &leftLen) && IsBalanced(pRoot->right, &rightLen)){
        int diff = leftLen - rightLen;
        if (diff <= 1 || diff >= -1){
            *depth = leftLen > rightLen ? leftLen + 1 : rightLen + 1;
            return true;
        }
    }
    return false;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325502502&siteId=291194637