1. 程式人生 > 其它 >專訪 KubeVela 核心團隊:如何簡化雲原生複雜環境下的應用交付和管理

專訪 KubeVela 核心團隊:如何簡化雲原生複雜環境下的應用交付和管理

236. 二叉樹的最近公共祖先

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

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

 

示例 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 。因為根據定義最近公共祖先節點可以為節點本身。

示例 3:

輸入:root = [1,2], p = 1, q = 2
輸出:1

 

提示:

  • 樹中節點數目在範圍 [2, 105] 內。
  • -109 <= Node.val <= 109
  • 所有 Node.val 互不相同 。
  • p != q
  • p 和 q 均存在於給定的二叉樹中。
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *dfs(TreeNode *node, TreeNode *p, TreeNode *q) { 13 if (node == p || node == q) { 14 return node; 15 } 16 if (node == nullptr) {
17 return nullptr; 18 } 19 TreeNode *left = dfs(node->left, p, q); 20 TreeNode *right = dfs(node->right, p, q); 21 if (left != nullptr && right != nullptr) { 22 return node; 23 } 24 if (left != nullptr) { 25 return left; 26 } 27 if (right != nullptr) { 28 return right; 29 } 30 return nullptr; 31 } 32 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 33 return dfs(root, p, q); 34 } 35 };