ch4.6: find the LCA of 2 nodes in a binary tree with 3 different methods

无法联网的情况下,dbeaver离线安装数据库驱动-clickhouse 阅读详情

In this problem, it is important to fully understand the definition of least common ancestor of 2 nodes:

it means: (from leetcode blog: 点击打开链接)

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

If you are not so sure about the definition of lowest common ancestor (LCA), please refer to my previous post:Lowest Common Ancestor of a Binary Search Tree (BST) or the definition of LCA here. Using the tree above as an example, the LCA of nodes 5 and 1 is 3. Please note that LCA for nodes 5 and 4 is 5.


Here is the whole code with comments. Really good design by Hawstein.

// Ch4.6: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. 
// Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.

//http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html
//the LCA of nodes 5 and 1 is 3. Please note that LCA for nodes 5 and 4 is 5.

#include 
  
   
#include 
   
    
#include 
    
     
#include 
     
using namespace std;

class BinNode{
public:
    int key;
    BinNode *parent, *lChild, *rChild;
    BinNode(){}
    BinNode(int t): key(t), parent(NULL), lChild(NULL), rChild(NULL){}
};

class BTree{
private:
    BinNode *m_root;
public:
    BTree(): m_root(NULL){}
    BTree(BinNode *t): m_root(t){}

    BinNode* getRoot() const{return m_root;}
    
    BinNode* balanceTree(BinNode* pnode, BinNode *parent, int *arr, int low, int high){
        if(low>high || arr == NULL)
            return NULL;
        int mid = (low+high)>>1;
        pnode = new BinNode(arr[mid]);
        pnode->parent = parent;
        pnode->lChild = balanceTree(pnode->lChild, pnode, arr, low, mid-1);
        pnode->rChild = balanceTree(pnode->rChild, pnode, arr, mid+1, high);

        return pnode;
    }

    void PrintPre(BinNode *pnode)
    {
        if(pnode == NULL)
            return;
 
        cout << pnode->key << " ";
        PrintPre(pnode->lChild);
        PrintPre(pnode->rChild);        
    }

    BinNode* minimal(BinNode* pnode){
        if(pnode==NULL) return NULL;
        while(pnode->lChild){
            pnode = pnode->lChild;
        }
        return pnode;
    }

    BinNode* successor(BinNode* qnode){
        if(qnode==NULL) return NULL;
        if(qnode->rChild) return minimal(qnode->rChild);
        BinNode *r = qnode->parent;
        while(r && r->rChild==qnode){
            qnode = r;
            r = r->parent;
        }
        return r;
    }
//  method 1: use a hash table to store the n1's parent to see if n2's parents are 
//  in the map. Learn to use map: key: pointer to the value, mapped value: the real data
    BinNode* firstAns(BinNode *n1, BinNode *n2){
        if(n1==NULL || n2==NULL) return NULL;
        map
      
        m;
        while(n1){
            m[n1] = true;
            n1=n1->parent;
        }
        while(n2 && !m[n2]){
            n2 = n2->parent;
        }
        return n2;
    }

//  method 2: recursively search for the commen father of (n1,n2). 
//  father method is use to see if (n1,n2) share the same father by going down:
//  n1->child->child->...->child. Only modify n1;
//  in the LCA recursively move n1 up 1 step until find (n1->p->p->...->p,n2) 
//  the same father. only modify n1;
//  By combining these 2 methods(one goes down, one goes up), n1 will search all the 
//  nodes in the tree to find the LCA to n2;
    bool father(BinNode *n1, BinNode *n2){
        if(n1==NULL || n2==NULL) return false;
        else if (n1==n2) return true;
        return (father(n1->lChild, n2) || father(n1->rChild, n2));
    }

    BinNode* firstAns2(BinNode *n1, BinNode *n2){
        if (n1==NULL || n2==NULL) return NULL;
        while(n1){
            if(father(n1,n2)) return n1;
            n1=n1->parent;
        }
        return NULL; // don't forget it.
    }

/*  method 3: if the node doesn't contain parent pointer(just don't use ->parent),
    then we can start from root and recursively. Carefully read the solution,: how 
    to update head, res. Use Node* &res, call by reference so will modify ans.
*/
    void firstAns3(BinNode *head, BinNode *n1, BinNode *n2, BinNode* &res){
        if (head==NULL || n1==NULL || n2==NULL) return;
        if(head && father(head, n1) && father(head, n2)){
            res = head;
            firstAns3(head->lChild, n1, n2, res);
            firstAns3(head->rChild, n1, n2, res);
        }
    }



// Auxilary methods:
    BinNode* searchND(BinNode* x_head, int x){
        if(x_head==NULL) return NULL;
        else if(x==x_head->key) return x_head;
        else if(x<=x_head->key) searchND(x_head->lChild, x);
        else searchND(x_head->rChild, x);
    }

    vector
       
        
         > BFSlist(BinNode *head){ vector
         
          
           > res; int level = 0; list
           
             li; li.push_back(head); res.push_back(li); while(!res[level].empty()){ list
            
              l; list
             
              ::iterator it; for(it=res[level].begin(); it!=res[level].end(); ++it){ BinNode *n = *it; if(n->lChild) l.push_back(n->lChild); if(n->rChild) l.push_back(n->rChild); } ++level; res.push_back(l); } return res; } void print(vector
              
               
                 > res){ vector
                
                 
                   >::iterator vit; for(vit=res.begin(); vit!=res.end(); ++vit){ list
                  
                    li = *vit; list
                   
                    ::iterator lit; for(lit=li.begin(); lit!=li.end(); ++lit){ BinNode *n = *lit; cout<
                    
                     key<<" "; } cout<
                     
                      balanceTree(bt->getRoot(), NULL, arr, low, high); bt = new BTree(proot); bt->PrintPre(bt->getRoot()); cout << "pnode is: "<< proot->key<
                      
                       successor(proot))->key<
                       
                        > jerry = bt->BFSlist(proot); bt->print(jerry); BinNode *n1 = bt->searchND(proot, 13); BinNode *n2 = bt->searchND(proot, 22); BinNode *n1_n2_ans = bt->firstAns(n1, n2); cout<
                        
                         key<<" "<
                         
                          key<
                          
                           key<
                           
                            firstAns2(n1, n2); cout<
                            
                             key<
                             
                              firstAns3(proot, n1, n2, result); cout<
                              
                               key<
                               
                              
                             
                            
                           
                          
                         
                        
                       
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
    
   
  

部署模型:Libtorch使用笔记【Pytorch的C++版本】【把用Pytorch训练好的模型打包保存为.pt格式,使用Libtorch去加载.pt格式模型,在C++工程中去用就好了】 A : Libtorch是pytorch的C++版本,现在的很多大型项目都是用C++写的,想使用训练好的模型,需要通过caffe等方式去集成,比较麻烦。这里pytorch官方提出了Libtorch,我们就可以把pytorch训练好的模型,打包起来,直接在C++工程中去用就好了,相比较caffe等,非常方便!虽然对于许多需要动态性和易迭代性的场景来说,Python是一种合适且首选的语言,但在同样的情况下,Python的这些特性恰恰是不利的。生产环境是一个需要低延迟和有严格部署要求的领域,一般选择C++。 阅读详情

相关推荐

保姆级教程:用Vue3+Element Plus快速搭建Flowable流程定义管理后台界面

本文提供了一份详细的Vue3+Element Plus教程,指导开发者快速搭建Flowable流程定义管理后台界面。从项目初始化、核心页面设计到响应式数据处理,全面覆盖前端开发关键步骤,帮助提升企业级应用开发效率。

weixin_42662293的博客 480

PAT1143 &1151 找LCA问题(刷题记录)

These two questions are similar.Both of them give traversal sequence of a binary tree and asks us to find the LCA(Lowest Common Ancestor) of some query pairs.

momoomoo的博客 198

Masta调用Geometry Modeller(Space Claim)进行根据三维模型快速建模设置方法

masta中调用ANSYS的space claim的设置方法

xifegnlie的博客 247

LCA in a Binary Tree

给出一棵树,求两个节点的最近公共祖先。 每次让两个点中深度大的点向上跳,直到两个点相交。很明显,当数据是一条链时,每次询问的时间复杂度可达到O(n)。 对于此题是采用的lca算法。 对于一棵普通的二叉树 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has b...

策马奔腾向前冲 274

顶刊论文引言用AI怎么写?借助Gemini 3 Pro结合四段式写出逻辑清晰的Introduction

写研究目标时,先明确研究问题,直接回应前文提到的研究缺口,如 “This study aims to investigate whether X modulates Y via the Z pathway in human cells.”然后再提出你的研究假设,当理论依据清晰时,可以用如 “We hypothesized that inhibiting X would rescue Y deficiency in this model.”的句子点出研究目标。要求:1)明确陈述本研究拟解决的核心科学问题;

智能AI让学术科研更容易 182

OpenGL 进阶系列10 - 光线跟踪实现简介(Ray Tracing)

OpenGL 实现光线跟踪(Ray Tracing)是一个相对复杂但有趣的挑战,通常用于生成高度逼真的图像效果,如反射、折射、阴影等。OpenGL 本身并不是为光线跟踪设计的,但可以通过结合计算着色器和现代 OpenGL 功能实现光线跟踪。光线跟踪的基本思路是从相机(或视点)出发,发射光线并计算这些光线与场景中物体的交点。光线与场景中物体相交的计算。计算交点的光照(基于表面法线、光源位置、材质等)。反射和折射的处理(如果物体是透明或反射的)。

GPU全栈博主 1535

1151 LCA in a Binary Tree (30 分)(C++)

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their LCA. In...

qq_41562704的博客 557

项目模块提取生成jar包上传到nexus供其他项目使用

项目场景: 微服务项目当中的某一个模块其他项目进行复用,资源管理搭建的有私服 nexus。 问题描述: 如果把功能用到其他项目,代码重复量太大,不想些重复的代码。 原因分析: 如果把这个模块单独提取出来进行复用,至于操作数据库的功能,使用远程调用进行数据库操作,这样就能解决相同模块重复编写的工作。量。 解决方案: 首先对模块代码进行封装提取,把一些用到的参数提取出来,以传参的形式来对参数进行传递。这个需要根据具体的情况进行代码提取,提取之后把这个模块的代码进行打包,打包可以借助开发工具进行打包(记得使用 d

lierjun 的专栏 451

PAT 1151 LCA in a Binary Tree——原理很简单,处理起来很麻烦

分析 找得到 LCA of 2 and 6 is 3. 8 is an ancestor of 1. 找不到 ERROR: 9 is not found. ERROR: 12 and -3 are not found. 找不到——》任意前序/中序搜索即可 找得到: LCA of 2 and 6 is 3. 分析中序可知:祖先3必在2,6中间 分析前序可知:祖先3必在2,6前面 因此同时满足上述2点,则说明能找到祖先 当不满足时,则说明情况为8 is an ancestor of 1

net961231的博客 196

AI原生应用评测:主流大语言模型性能对比

任务适配性:是否匹配应用的核心任务(如代码生成需强逻辑推理,内容创作需强创意性);上下文能力:处理长序列(如10万+字文档)的理解与生成能力;可靠性:幻觉(Hallucination)率、事实准确性、安全合规性;性价比:API调用成本、延迟、 scalability(扩展能力)。AI原生应用的核心是LLM与应用场景的深度协同。

架构师的AI之路,分享AI应用开发架构的学习与实践。 508

【短距离通信】【WiFi】精讲802.11n/ac/ax mpdu和ampdu最大长度

在 Wi-Fi 标准(802.11n、802.11ac 和 802.11ax)中,和是数据传输的核心概念。理解它们各自的作用以及不同标准下的最大长度限制,有助于深入了解 Wi-Fi 的性能优化机制。以下是对802.11n802.11ac和802.11ax中MPDU和A-MPDU最大长度的详细技术分析和对比。1. MPDU 和 A-MPDU 的基本概念MPDU 是经过 MAC 层处理后的数据单元,主要由MAC层数据帧和物理层的传输头部(PHY headers)组成。

风云说通信 1109

1151 LCA in a Binary Tree 一种自己的解法

最近刷PAT的题目看到一个BST找最近共同祖先的新思路,大大化简了算法,给出链接: https://blog.csdn.net/ysq96/article/details/81746996 因为这种解法只适合BST且需要先序排序,所以只能针对A1143这种题目,根据这个思路对于A1151我进行了算法的迁移使用: 将原来的树映射到一棵BST上,在BST上找到答案后映射回由原来的树,在此贴上代码...

superstar_zbt的博客 648

YOLO26剪枝 lamp剪枝测试精度仅掉0.7个点,速度提高11.8fps!

针对没有如何去选择剪枝的内容LAMP是层自适应幅度调整剪枝,无需任何参数,通过算法内部自己计算每个层的重要程度进行剪枝。基于权重重要程度和该层权重大小关系,权重越大表明该层越重要的思想进行优化。这个跟我前面说的非结构化全局剪枝是一个解法(MP),也就是lamp是在我前面那个非结构化剪枝的基础上进行优化的。但是这个逐层进行非结构剪枝目前还没有一个清晰的概念,确定每个层要剪枝多少。LAMP得分是一个平方权重大小,由层中所有“幸存权重”的总和归一化。

m0_64661770的博客 677

1151 LCA in a Binary Tree (30 分)

首先是鬼鬼珊的闲聊一分钟 今天给大家扯一点什么呢?好吧,最近的论文看得我想哭,最悲伤的事是看不懂呀,尤其是国外研究的论文,一个句子长到我还要进行英文的长难句解析才勉强搞得清楚其中的深刻含义,导致我每天都想躺尸。说起来还有一件事值得一提,很久之前和朋友聊天,说起恋爱这个事,她以一个过来人的经验告诉我,在恋爱中尽量不要作,不要乱发脾气。因此,我为了促进自我良好的恋爱发展进行了深刻的调研,调研平...

超级酷的鬼鬼珊 522

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

1151 LCA in a Binary Tree(30 分)

1151 LCA in a Binary Tree(30 分) The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you ar...

galesaur_wcy 281

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

PAT 1151 LCA in a Binary Tree (建树+lca)

1151LCA in a Binary Tree(30分) The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their LCA. Input Specification: Eac..

YIU 207

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

1151 LCA in a Binary Tree

没怎么写过树,欠的还是要还的。 目前看了题解是两种做法,一种是直接找,另一种是先建树再LCA(LCA用的裸查找)。 直接查找 a和b的最近公共祖先一定在中序遍历a的位置和中序遍历b的位置之间,而a和b的公共祖先一定在先序遍历中a和b的位置之前。在先序遍历中从0开始查找,找到的第一个中序遍历位置位于a和b之间的就是最近公共祖先。 #include <iostream> #include <algorithm> #include <stdio.h> #include <

Erin2333的博客 323

1151 LCA in a Binary Tree (30分)(中序求LCA)

【题意】 给定一棵树的中序和前序,给出q个询问,每个询问两个点u,v,询问u,v的最近公共祖先。 【题解】 不需要建整颗树,在左根右这样的中序时,如果两个结点分别在根的左右(可包含根),那么根即是LCA;如果两个结点同时在根的左边,那么我们继续遍历左子树;否则继续遍历右子树。 【代码】 #include <bits/stdc++.h> using namespace std...

菜鸡成长史 452

LCA in a Binary Tree(貌似不是正解

给出中序遍历和先序遍历求俩节点的LCA The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to ...

资深罚时选手 295

1151 LCA in a Binary Tree (30 分)

1、题面: https://pintia.cn/problem-sets/994805342720868352/problems/1038430130011897856 2、题意: 给出树的中序、前序,然后询问u,v的lca 3、正解: 1、不建树,直接递归查找 https://blog.csdn.net/liuchuo/article/details/82560863 2、建树,并查...

九大于七的博客 566

PAT 1151 LCA in a Binary Tree(30 分)- 甲级

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their LCA. In...

柳婼 の blog 9113

1151 LCA in a Binary Tree (30分)

自己写的: 先建树,然后利用后续非递归遍历求解 #include<iostream> #include<stack> using namespace std; const int maxn = 10010; typedef struct node { int n; node* left; node* right; }*tree; int n, m, pre[maxn...

自己人的博客 281

1151 LCA in a Binary Tree (30分) 树、LCA、前序中序确定树。两种思路。

题目链接 1151 LCA in a Binary Tree (30分) The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their LCA. Input Specification: Ea

jetpack_的博客 224

pta--1151 LCA in a Binary Tree(30 分)(二叉树 LCA 模板题)

1151 LCA in a Binary Tree(30 分) The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you a...

来啦(#^.^#) 1254

1151 LCA in a Binary Tree (30 分)

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their LCA. In...

石前有座桥的博客 359
上一篇: Ch4.5: find the (in-order tranversely) successor of a node in BST.
下一篇: 1/22/2014: 纪念第一个C++ programmer电面--F家
纯黑老白
博客等级 码龄18年 30粉丝 62原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值