【LeetCode】Maximum Depth of Binary Tree && Minimum Depth of Binary Tree

来源:互联网 发布:威戈背包知乎 编辑:程序博客网 时间:2024/06/07 15:43
1、Maximum Depth of Binary Tree
Total Accepted: 10889 Total Submissions: 24617 My Submissions
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Have you been asked this question in an interview?  Yes
Discuss
2、Minimum Depth of Binary Tree
Total Accepted: 8209 Total Submissions: 28728 My Submissions
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Have you been asked this question in an interview?  Yes
Discuss
        min和max其实不大一样。
        max到叶子节点,最长路程,其实是一直深度搜索的过程。
        min,需要判断当前是否为叶子节点,这个很重要。

MAX Java AC

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int maxDeep;    public int maxDepth(TreeNode root) {        if(root == null){            return 0;        }        maxDeep = 0;        dfs(root, 1);        return maxDeep;    }    public void dfs(TreeNode root, int deep){        if(root == null){            return;        }        maxDeep = Math.max(maxDeep, deep);        dfs(root.left, deep+1);        dfs(root.right, deep+1);    }}

MIN Java AC

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int minDeep;    public int minDepth(TreeNode root) {        if(root == null){            return 0;        }        minDeep = Integer.MAX_VALUE;        dfs(root, 1);        return minDeep;    }    public void dfs(TreeNode root, int deep){        if(root.left == null && root.right == null){            minDeep = Math.min(minDeep, deep);            return;        }        if(root.left != null){            dfs(root.left, deep+1);        }        if(root.right != null){            dfs(root.right, deep+1);        }    }}

0 0
原创粉丝点击