Sword Finger Offer Interview Question 55-1: The depth of the binary tree

A very simple question, the answer does not use global variables, better

 

 

class Solution {
    int max_dep=0;
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        findDepth(root,1);
        return max_dep;
    }

    public void findDepth(TreeNode root,int cur_dep){
        if(cur_dep > max_dep){
            max_dep = cur_dep;
        }
        if(root.left!=null){
            findDepth(root.left,cur_dep+1);
        }

        if(root.right!=null){
            findDepth(root.right,cur_dep+1);
        }
    }
}

 

answer

public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

 

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/115000349