当前位置:网站首页>Force buckle -104 Maximum depth of binary tree

Force buckle -104 Maximum depth of binary tree

2022-06-25 09:42:00 Struggling young man

104. The maximum depth of a binary tree

difficulty : Simple

Ideas : Define two variables , Respectively used to save the maximum depth of the binary tree , And the depth of the current traversal . Then define a traverse function , Used to traverse the binary tree .

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
    

    // Define a variable to hold the maximum depth 
    int maxDtph = 0;
    // Define a variable to hold the current traversal depth  levelDth
    int levelDth = 0;
    public int maxDepth(TreeNode root) {
    
        traverse(root);
        return maxDtph;
    }
    // Define a function to traverse a binary tree 
    void traverse(TreeNode root){
    
        // Boundary value judgment 
        if(root == null){
    
            return ;
        }
        // depth +1
        levelDth++;
        // If the current traversal reaches the depth   Greater than   Used to record the depth of binary tree   Value . Then assign this value to maxDtph
        if(levelDth > maxDtph){
    
            maxDtph = levelDth;
        }
        traverse(root.left);
        traverse(root.right);
        // After the sequence traversal 
        levelDth--;
    }
}
Tips

The idea of traversal recursion is used

原网站

版权声明
本文为[Struggling young man]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250851230483.html