1. 程式人生 > 實用技巧 >Arduino ESP32 WiFi功能

Arduino ESP32 WiFi功能

技術標籤:劍指Offer二叉樹資料結構演算法

一、需求

  • 給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。

  • 百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”

  • 例如,給定如下二叉樹:root =[3,5,1,6,2,0,8,null,null,7,4]。

示例 1:

輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
輸出: 3
解釋: 節點 5 和節點 1 的最近公共祖先是節點 3。
示例2:

輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
輸出: 5
解釋: 節點 5 和節點 4 的最近公共祖先是節點 5。因為根據定義最近公共祖先節點可以為節點本身。

說明:

所有節點的值都是唯一的。
p、q 為不同節點且均存在於給定的二叉樹中。

二、後序遍歷(DFS)

2.1 思路分析

  1. 若root是p、q的公共祖先,則只有三種情況:①p、q在root的左右子樹,分列root的異側;②p = root,q在root左或右子樹中;③q = root,p在root的左或右子樹中;
  2. 考慮利用後序遍歷,自底向頂回溯,最後返回公共祖先root即可;
  3. 首先是初始化,當root == null時,或root == p時,或root == q時,這些情況都要返回root;
  4. 步驟3不成立,說明當前root不是公共祖先,遞迴root.left,root.right,令遞迴左子樹的結果為left,遞迴右子樹的結果為right;
  5. ①left、right同時為null,說明沒有找的公共祖先,直接返回null;②left == null,right != null,說明p,q在左子樹,直接返回left;③left != null,right == null,說明p,q在右子樹,直接返回right;④left != null,right != null,說明p,q分別在root的左、右子樹,此時返回root;

2.2 程式碼實現

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left == null && right == null) return null;
        if(left != null && right != null) return root;
        if(left == null && right != null) return right;
        if(left != null && right == null) return left;
        return root;
    }
}

2.3 程式碼優化

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left == null) return right;
        if(right == null) return left;
        return root;
    }
}

2.4 複雜度分析

  • 時間複雜度為O(N),其中N為二叉樹的節點數,最差情況下,需要遞迴遍歷所有的節點;
  • 空間複雜度為O(N),最差情況下,二叉樹退化為連結串列,遞迴的深度可達N;

三、學習地址

作者:Krahets

連結:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/solution/mian-shi-ti-68-ii-er-cha-shu-de-zui-jin-gong-gon-7/