LeetCode111:二叉树的最小深度

    技术2022-07-20  67

    /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int minDepth(TreeNode root) { LinkedList<Pair<TreeNode,Integer>> ans = new LinkedList<>(); if(root == null){ return 0; } else{ ans.add(new Pair<>(root,1)); } int depth = 0; while(!ans.isEmpty()){ Pair<TreeNode,Integer> cur = ans.poll(); TreeNode r = cur.getKey(); depth = cur.getValue(); if(r.left == null && r.right == null){ break; } if(r.left != null){ ans.add(new Pair<>(r.left, depth + 1)); } if(r.right != null){ ans.add(new Pair<>(r.right,depth + 1)); } } return depth; } }

     

    Processed: 0.008, SQL: 9