二叉树的最大深度

对称二叉树
  https://leetcode.cn/problems/symmetric-tree/
  给你一个二叉树的根节点 root , 检查它是否轴对称。
1Solution BFS Accepted / Used 时空复杂度 O(n) O(n)

//用栈实现即可
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        LinkedList<N> list = new LinkedList<>();
        list.push(new N(1,root));
        int max = 1;
        N rt;
        while(!list.isEmpty()) {
            rt = list.pop();
            if(rt.p.left!=null) {
                max = Math.max(max,rt.val+1);               
                list.push(new N(rt.val+1,rt.p.left));
            }
            if(rt.p.right!=null) {
                max = Math.max(max,rt.val+1);
                list.push(new N(rt.val+1,rt.p.right));
            }
        }
        return max;

    }
}
class N {
    int val;
    TreeNode p;
    public N() {}
    public N(int val,TreeNode p) {
        this.val = val;
        this.p = p;
    }
}

2 Solution DFS Accepted / Used 时空复杂度 O(n) O(height)
递归的含义:
  max(l,r)+1,定义一个f(t),返回最大深度,每层都加一即可
  height 表示最大深度,每层消耗O(1) 空间

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

3 Solution BFS 官方版 Accepted / Used 时空复杂度 O(n) O(n)
递归的含义:

// <>BFS使用队列实现, 严格使用 list.add(), list.poll()
//<>DFS使用栈实现,严格使用 list.push(), list.pop()=
//<>BFS用到DFS的方法 或者 DFS用到BFS的方法 结果很容易出错

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);
        int ans = 0, len = 0;
        TreeNode nd;
        while(!list.isEmpty()) {
            len = list.size();//利用长度的也可以确定每一层有多少个节点,以此算出最大深度
            for(int i = 0; i < len; ++i) {
                nd = list.poll();
                if (nd.left != null) list.add(nd.left); 
                if (nd.right != null) list.add(nd.right);    
            } 
            ans++;
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值