Application examples of the core idea of binary tree: binary tree mirroring/depth of binary tree/balanced binary tree

The most classic recursive routine about Tree

Use the main function to pass parameters root.left and root.right, and save them with a reference.
At the same time, you should also pay attention to the return value and the return result

Sword refers to Offer 27. Mirror image of binary tree

Please complete a function that takes as input a binary tree and the function outputs its mirror image.

class Solution {
    
    
    public TreeNode mirrorTree(TreeNode root) {
    
    
        // 首先进行判空操作
        if(root == null){
    
    
            return null;
        }
        TreeNode l = mirrorTree(root.left);
        TreeNode r = mirrorTree(root.right);

        // 左右互换
        root.left = r;
        root.right = l;

        return root;
    }
}

The sword refers to Offer 55 - I. The depth of the binary tree

class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root==null){
    
    
            return 0;
        }
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        if(l>r){
    
    
            return l+1;
        }else {
    
    
            return r+1;
        }
    }
}

Sword Pointer Offer 55 - II. Balanced Binary Tree

Balanced binary tree: the height difference between the left and right subtrees of any node does not exceed 1

class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root==null){
    
    
            return 0;
        }
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        if(l>r){
    
    
            return l+1;
        }else {
    
    
            return r+1;
        }
    }
    public boolean isBalanced(TreeNode root) {
    
    
        if(root==null){
    
    return true;}
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        
        return Math.abs(l-r)<=1 && isBalanced(root.left) && isBalanced(root.right);
    }
}

Guess you like

Origin blog.csdn.net/qq_39537400/article/details/124024269