Tree-----求树的最大深度和最小深度(104. Maximum Depth of Binary Tree 111. Minimum Depth of Binary Tree)

来源:互联网 发布:河北农业科技网络书屋 编辑:程序博客网 时间:2024/05/19 21:17

1.最大深度

原题目

public class Solution {    public int maxDepth(TreeNode root) {        if (root == null) {            return 0;        }        int a = 0, b = 0;        if (root.left != null) {            a = maxDepth(root.left) + 1;        }        if (root.right != null) {            b = maxDepth(root.right) + 1;        }        //只有一个节点的特殊情况        if (a == 0 && b == 0) {            return 1;        }        if (a > b) {            return a;        } else {            return b;        }    }}

2.最小深度

    public int minDepth(TreeNode root) {        if (root == null) {            return 0;        }        if (root.left == null) {            return minDepth(root.right) + 1;        }        if (root.right == null) {            return minDepth(root.left) + 1;        }        return Math.min(minDepth(root.right), minDepth(root.left)) + 1;    }
0 0
原创粉丝点击