Leetcode104. 二叉树的最大深度

1.递归解法

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

2.迭代法
这种方法和求102题的层序遍历方法差不多,

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        Queue<TreeNode> queue = new ArrayDeque<>();//队列来存放root
        queue.add(root);
        int max=0;//存放深度,相当于层序遍历中的数组中数组的个数,
        while(!queue.isEmpty()){//当队列不为空的时候
            max++;           
            int n = queue.size();
            for(int i=0;i<n;i++){
                TreeNode node=queue.poll();//把一个队列的节点取出来,然后在队列最后的位置加上这个节点的左右子树,相当于层序遍历中的(把树的某一层进行处理),n就是表示这一层有多少个节点,依次把这一层的节点取出来,然后吧下一层的节点按照左右顺序添加到队列的尾部           
                if(node.left!=null) queue.add(node.left);
                if(node.right!=null) queue.add(node.right);

            }
        }
        return max;
    }
}

你可能感兴趣的:(数据结构)