Minimum Depth of Binary Tree (Java)

来源:互联网 发布:app.js 代码大全 编辑:程序博客网 时间:2024/05/16 09:30

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.

Source

public int minDepth(TreeNode root) {                int left = 0;        int right = 0;                if(root == null) return 0;        if(root.left == null && root.right == null){        return 1;        }                if(root.left == null){        left = Integer.MAX_VALUE;//Integer.MAX_VALUE        }        else left = minDepth(root.left);                if(root.right == null){        right = Integer.MAX_VALUE;//注意 这类情况是有一个孩子的 不能算是路径        }        else right = minDepth(root.right);                return Math.min(left, right) + 1;    }

Test

public static void main(String[] args){    TreeNode a = new TreeNode(5);    a.left = new TreeNode(4);    a.right = new TreeNode(8);    a.left.left = new TreeNode(11);    a.left.left.left = new TreeNode(7);    a.left.left.right = new TreeNode(2);    a.right.left = new TreeNode(13);    a.right.right = new TreeNode(4);    a.right.right.right = new TreeNode(1);    System.out.println(new Solution().minDepth(a));    }


0 0
原创粉丝点击