1. 程式人生 > >C#LeetCode刷題之#104-二叉樹的最大深度​​​​​​​(Maximum Depth of Binary Tree)

C#LeetCode刷題之#104-二叉樹的最大深度​​​​​​​(Maximum Depth of Binary Tree)

問題

給定一個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

說明: 葉子節點是指沒有子節點的節點。 給定二叉樹 [3,9,20,null,null,15,7],

       3       / \    9   20   /        \ 15        7

返回它的最大深度 3 。

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.

Note: A leaf is a node with no children.

Given binary tree [3,9,20,null,null,15,7],

       3       / \    9   20   /        \ 15        7

return its depth = 3.

示例

public class Program {

    public static void Main(string[] args) {
        var p = new TreeNode(1) {
            left = new TreeNode(2)
        };

        var q = new TreeNode(1) {
            left = new TreeNode(2)
        };

        var res = IsSameTree(p, q);
        Console.WriteLine(res);

        q.right = new TreeNode(6);

        res = IsSameTree2(p, q);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    public static void IsSame(TreeNode p, TreeNode q, ref bool isSameTree) {
        //先序遍歷分析法
        if(p?.val != q?.val) {
            isSameTree = false;
            return;
        }
        if(p != null && q != null) {
            if(p.left != null || q.left != null) {
                IsSame(p.left, q.left, ref isSameTree);
            }
            if(p.right != null || q.right != null) {
                IsSame(p.right, q.right, ref isSameTree);
            }
        }
        return;
    }

    public static bool IsSameTree(TreeNode p, TreeNode q) {
        var isSameTree = true;
        IsSame(p, q, ref isSameTree);
        return isSameTree;
    }

    public static bool IsSameTree2(TreeNode p, TreeNode q) {
        //優雅遞迴法
        //如果 p 和 q 同時為空,則肯定相
        //已經到了遞迴最底層的呼叫,也就是遞迴的最基本情況
        //屬於遞迴的終止條件
        //以下3行程式碼均是終止條件
        if(p == null && q == null) return true;
        //如果 p 為空,q 不為空,則肯定不相同
        if(p == null) return false;
        //如果 q 為空,p 不為空,則肯定不相同
        if(q == null) return false;
        //遞迴呼叫
        return p.val == q.val &&
                IsSameTree2(p.left, q.left) &&
                IsSameTree2(p.right, q.right);
    }

    public class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int x) { val = x; }
    }

}

以上給出2種演算法實現,以下是這個案例的輸出結果:

True
False

分析:

顯而易見,以上2種演算法的時間複雜度均為: O(n) 。