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.

  • 層次遍歷法
public class MinimumDepthOfBinaryTree {
    static boolean isLeaf(TreeNode root){
        if(root.left == null && root.right == null){
            return true;
        }
        return false;
    }   
    public static int run(TreeNode root) {  
        if(root != null){
            TreeNode temRoot;
            int count = 0;
            Queue<TreeNode> queue = new LinkedList<>(); 
            queue.add(root);
            root.val = 1;
            while(queue.size() != 0){
                temRoot = queue.poll();
                int layer = temRoot.val;
                if(isLeaf(temRoot)){
                    return layer;
                }
                if(temRoot.left != null){
                    queue.add(temRoot.left);
                    temRoot.left.val = temRoot.val + 1;
                }
                if(temRoot.right != null){
                    queue.add(temRoot.right);
                    temRoot.right.val = temRoot.val + 1;
                }
            }
        }
      return 0;
    }
    private static void build(TreeNode root) {
        // TODO Auto-generated method stub
        setLeft(root);
        setRight(root);
        setLeft(root.left);
        setLeft(root.right);
    }
    public static void setLeft(TreeNode root){
        root.left = new TreeNode(0);
    }
    public static void setRight(TreeNode root){
        root.right = new TreeNode(0);
    }
    //運用層次遍歷計算
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(0);
        build(treeNode);
        System.out.println(run(treeNode));;
    }
  • 用層次遍歷方法很簡單,但是用深度遍歷法則需要好好思考思考,遞歸就是整體考慮,就把run當做了求最小值的方法
class Solution {
public:
    int run(TreeNode *root) 
    {
        if(root == nullptr) return 0;
        if(root->left == nullptr) // 若左子樹為空,則返回右子樹的最小深度+1
        {
            return run(root->right)+1;
        }
        if(root->right == nullptr) // 若右子樹為空,則返回左子樹的最小深度+1
        {
            return run(root->left)+1;
        }
        // 左右子樹都不為空時,取較小值
        int leftDepth = run(root->left);
        int rightDepth = run(root->right);
        return (leftDepth<rightDepth)?(leftDepth+1):(rightDepth+1);
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容