以236. 二叉树的最近公共祖先为例子
本地编译软件为Viusal Studio 2022
写代码
项目里文件位置
CreateTree.h
#pragma once
#ifndef CLIONPROJECT_LEETCODECREATETREE_H
#define CLIONPROJECT_LEETCODECREATETREE_H
#include<vector>
#include<queue>
using namespace std;
struct TreeNode
{int val;TreeNode* left;TreeNode* right;TreeNode() : val(0), left(nullptr), right(nullptr) {}TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};TreeNode* createTree(vector<int> nodes)
{if (!nodes.size()){return nullptr;}queue<TreeNode*> que;TreeNode* root, * node, * cur;root = new TreeNode();cur = new TreeNode();bool is_left = true;for (auto val : nodes){if (val != INT_MAX){node = new TreeNode(val);}else{node = nullptr;}if (que.empty()){root = node;que.push(node);}else if (is_left){cur = que.front();que.pop();cur->left = node;if (&node){que.push(node);}is_left = !is_left;}else{cur->right = node;if (&node){que.push(node);}is_left = !is_left;}}return root;
}#endif //CLIONPROJECT_LEETCODECREATETREE_H
236_二叉树的最近公共祖先.cpp
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include "CreateTree.h"using namespace std;class Solution {
public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){if (root->val == q->val || root->val == p->val || root == NULL){return root;}TreeNode* left = lowestCommonAncestor(root->left, p, q);TreeNode* right = lowestCommonAncestor(root->right, p, q);if (left != NULL && right != NULL){return root;}if (left == NULL && right == NULL){return right;}else if (left != NULL && right == NULL){return left;}else // (left == NULL && right == NULL){return NULL;}}
};int main()
{vector<int> input = {3,5,1,6,2,0,8,INT_MAX,INT_MAX,7,4};TreeNode* root;TreeNode* p = new TreeNode(5);TreeNode* q = new TreeNode(1);root = createTree(input);Solution solution = Solution();TreeNode* result = solution.lowestCommonAncestor(root, p, q);cout << result->val << endl;return 0;
}
FBI WARNING:
(1)输入的是一串int
,所以把其中null
改成正常节点用不到的一个值;
(2)输入的p
和q
是指向实际那个节点的(指向树中那个位置),但是自己创建数有点麻烦,所以我重新创建了一个节点,就必须要在后面遍历逻辑中比较是否找到的时候,改成root->val == p->val
,不可以是root == p
;
接下来就可以愉快的调试了!
参考
力扣二叉树题目本地测试生成测试用例Python\C++