LeetCode—二叉樹最短路徑

題目:

leetcode-Minimum Depth of Binary Tree

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.

輸入一個二叉樹,求根節點到葉子節點的最短路徑的節點個數。

思路

1、遞歸解法,分別求左右子樹深度,左右子樹深度的較小值加1即爲最終深度。需要注意左節點/右節點爲空時,需要返回根節點到右節點/左節點的深度。
2、非遞歸解法,從根節點開始按層遍歷,疊加level直到葉子節點。

Java 實現


/**
*先定義樹節點
*/ 
public class TreeNode {
    private int value;

    private TreeNode left;

    private TreeNode right;

    public TreeNode(int value) {
        this.value = value;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }
}


/**
*算法實現類
*/
public class MinDepthOfTree {
    /**
     * 遞歸法
     * @return
     */
    public static int getDepthRecursion(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = getDepthRecursion(root.getLeft());
        int right = getDepthRecursion(root.getRight());

        //需要注意左節點/右節點爲空時,需要返回根節點到右節點/左節點的深度
        if (left == 0 || right == 0) {
            return 1 + left + right;
        }
        return left < right ? left + 1 : right + 1;
    }

    /**
     * 思路:
     * 非遞歸
     * 1、從根節點開始按層遍歷二叉樹.
     * 2、遍歷到該層時,判斷當前節點是否爲葉子節點,是葉子節點則找到了最小深度並返回,否則添加子節點到隊列中.
     * @return
     */
    public static int getDepthNoRecursive(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
        nodeQueue.offer(root);
        int level = 0;

        while (!nodeQueue.isEmpty()) {
            level ++ ;
            int size = nodeQueue.size();
            for (int i = 0; i< size; i++) {
                TreeNode node = nodeQueue.poll();
                if (node.getLeft() == null && node.getRight() == null) {
                    return level;
                }
                if (node.getLeft() != null) {
                    nodeQueue.offer(node.getLeft());
                }
                if (node.getRight() != null) {
                    nodeQueue.offer(node.getRight());
                }
            }
        }
        return level;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章