首页 > 其他分享 >236. 二叉树的最近公共祖先c

236. 二叉树的最近公共祖先c

时间:2024-03-21 17:02:10浏览次数:20  
标签:right TreeNode struct 祖先 二叉树 return 236 root left

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if(!root) return NULL;
    if(root==p || root==q) return root;
    struct TreeNode* left=lowestCommonAncestor(root->left,p,q);
    struct TreeNode* right=lowestCommonAncestor(root->right,p,q);
    if(left && right) return root;
    if(left) return left;
    if(right) return right;
    if(!left && !right){
        if(root==p || root==q) return root;
    }

    return NULL;
}

 

标签:right,TreeNode,struct,祖先,二叉树,return,236,root,left
From: https://www.cnblogs.com/llllmz/p/18087771

相关文章

  • 257. 二叉树的所有路径c
    /***Definitionforabinarytreenode.*structTreeNode{*intval;*structTreeNode*left;*structTreeNode*right;*};*//***Note:Thereturnedarraymustbemalloced,assumecallercallsfree().*/inttemp[400];voiddf......
  • 【数据结构和算法初阶(C语言)】二叉树的顺序结构--堆的实现/堆排序/topk问题详解---二
     目录 ​编辑1.二叉树的顺序结构及实现1.1二叉树的顺序结构2堆的概念及结构3堆的实现3.1堆的代码定义3.2堆插入数据3.3打印堆数据3.4堆的数据的删除3.5获取根部数据3.6判断堆是否为空3.7堆的销毁 4.建堆以及堆排序 4.1堆排序---是一种选择排序4.2升......
  • 代码随想录第15天|二叉树的层序遍历
    二叉树的层序遍历102.二叉树的层序遍历-力扣(LeetCode)代码随想录(programmercarl.com)讲透二叉树的层序遍历|广度优先搜索|LeetCode:102.二叉树的层序遍历_哔哩哔哩_bilibili给你二叉树的根节点 root ,返回其节点值的 层序遍历 。(即逐层地,从左到右访问所有节点)......
  • 代码随想录第14天|二叉树的递归遍历
    二叉树的理论基础代码随想录(programmercarl.com)关于二叉树,你该了解这些!|二叉树理论基础一网打尽,二叉树的种类、二叉树的存储方式、二叉树节点定义、二叉树的遍历顺序_哔哩哔哩_bilibili二叉搜索树:二叉搜索树是一个有序树。左子树不为空,则左子树上所有节点的值均小于根......
  • Leecode 二叉树的中序遍历
    Day6第三题这是一道让我崩溃的题,因为一个笔误root.right写成了root.left改了好久。classSolution{publicList<Integer>inorderTraversal(TreeNoderoot){List<Integer>listRoot=newArrayList<Integer>();if(root!=null){listRo......
  • 102. 二叉树的层序遍历C
    /***Definitionforabinarytreenode.*structTreeNode{*intval;*structTreeNode*left;*structTreeNode*right;*};*//***Returnanarrayofarraysofsize*returnSize.*Thesizesofthearraysarereturnedas*returnC......
  • 代码随想录算法训练营第十五天| 226. 翻转二叉树 101. 对称二叉树
    226.翻转二叉树https://leetcode.cn/problems/invert-binary-tree/description/publicTreeNodeinvertTree(TreeNoderoot){invert(root);returnroot;}publicvoidinvert(TreeNodenode){if(node==null)return;TreeNod......
  • 51nod2599 最近公共祖先LCA
    给定一颗n个节点的树,根节点编号为1,有Q组询问,每次给定一对节点编号(x,y),求(x,y)的最近公共祖先。求LCA有多种方法,这里给的是倍增法,预处理时间O(nlogn),单次查询时间O(logn),支持在线。#include<bits/stdc++.h>usingnamespacestd;#defineintlonglong#definerep(i,a,b)for......
  • 洛谷题单指南-二叉树-P1185 绘制二叉树
    原题链接:https://www.luogu.com.cn/problem/P1185题意解读:在表格中绘制二叉树,有几个关键点1、结点用小写字母o 表示,对于一个父亲结点,用 / 连接左子树,用 \连接右子树,表格其余地方填空格。2、第m层结点若两个属于同一个父亲,那么它们之间由 3个空格隔开;若两个结点相邻但......
  • 第七节:二叉树的先序、中序、后续遍历的多种递归写法
    一.        二.        三.         !作       者:Yaopengfei(姚鹏飞)博客地址:http://www.cnblogs.com/yaopengfei/声     明1:如有错误,欢迎讨论,请勿谩骂^_^。声     明2:原创博客请在转载......