1. 程式人生 > >LeetCode 236. 二叉樹的最近公共祖先

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

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

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

說明:

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

個人思路在於先求出root到兩個節點的路徑上所需要路過的節點,分別用vecLeft和vecRight來儲存,然後再找出兩個陣列中第一個相同值,程式碼如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
static const auto init = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (p == root || q == root) // p或q當中有一個是根節點,則根節點為兩者的公共祖先
			return root;
		// // 先查詢從根節點到p所經過的所有節點
		vector<TreeNode*> vecLeft;
		this->findTreeNodePath(root, p, vecLeft);
		vector<TreeNode*> vecRight;
		this->findTreeNodePath(root, q, vecRight);
        int size1 = vecLeft.size();
		int size2 = vecRight.size();
		if (size1 == size2)
		{
			for (int i = 0; i < size1; i++)
			{
				if (vecLeft[i] == vecRight[i])
				{
					return vecLeft[i];
				}
			}
		}
		else
		{
			for (int i = 0; i < size1; i++)
			{
				for (int j = 0; j < size2; j++)
				{
					if (vecRight[j] == vecLeft[i])
						return vecLeft[i];
				}
			}
		}
		return root;
    }
    
    // 從根節點到指定節點之間的路徑,用陣列儲存
	TreeNode* findTreeNodePath(TreeNode* root, TreeNode* targetNode, vector<TreeNode*> & vec)
	{
		if (root == NULL || targetNode == NULL)
			return NULL;
		if (root != targetNode)
		{
			TreeNode* node = this->findTreeNodePath(root->left, targetNode, vec);
			if (node != NULL)
			{
				vec.push_back(root);
			}
			else
			{
				node = this->findTreeNodePath(root->right, targetNode, vec);
				if (node != NULL)
					vec.push_back(root);
			}
			return node;
		}
		else
		{
			vec.push_back(root);
			return root;
		}
		return NULL;
	}
};