当前位置:网站首页>LeetCode:236. The nearest common ancestor of binary tree
LeetCode:236. The nearest common ancestor of binary tree
2022-07-06 08:51:00 【Bertil】
Given a binary tree , Find the nearest common ancestor of the two specified nodes in the tree .
In Baidu Encyclopedia, the most recent definition of public ancestor is :“ For a tree T Two nodes of p、q, The nearest common ancestor is represented as a node x, Satisfy x yes p、q Our ancestors and x As deep as possible ( A node can also be its own ancestor ).”
Example 1:
Input :root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output :3
explain : node 5 And nodes 1 The most recent public ancestor of is the node 3 .
Example 2:
Input :root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output :5
explain : node 5 And nodes 4 The most recent public ancestor of is the node 5 . Because by definition, the nearest common ancestor node can be the node itself .
Example 3:
Input :root = [1,2], p = 1, q = 2
Output :1
Tips :
- The number of nodes in the tree is in the range [2, 10^5] Inside .
- -10^9 <= Node.val <= 10^9
- all Node.val Different from each other .
- p != q
- p and q All exist in a given binary tree .
Their thinking
1. First use recursion :root yes null perhaps root be equal to p or q, explain root yes p,q The common ancestor of ( Recursion ends ), So as to recurse the left and right subtrees
2. Then judge after the recursion of the left and right subtrees
- If the left and right subtree recursive functions do not return empty , be root Namely p,q The common ancestor of
- If the value returned by the left subtree recursive function is null , be p,q All in the right subtree , Go straight back to right that will do
- If the value returned by the right subtree recursive function is null , be p,q It's all in zuozhu , Go straight back to left that will do
Code
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */
/** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} q * @return {TreeNode} */
var lowestCommonAncestor = function(root, p, q) {
const travelTree = function(root, p, q) {
// Recursive termination condition
if(root === null || root === p|| root === q) {
return root;
}
let left = travelTree(root.left, p, q);
let right = travelTree(root.right, p, q);
// If you can find both the left and right subtrees of a node p and q, This indicates that this node is a common ancestor
if(left !== null && right !== null) {
return root;
}
if(left === null) {
return right;
}
return left;
}
return travelTree(root, p, q);
};
边栏推荐
- Process of obtaining the electronic version of academic qualifications of xuexin.com
- Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)
- Compétences en mémoire des graphiques UML
- Warning in install. packages : package ‘RGtk2’ is not available for this version of R
- Chapter 1 :Application of Artificial intelligence in Drug Design:Opportunity and Challenges
- hutool优雅解析URL链接并获取参数
- egg. JS project deployment online server
- pytorch查看张量占用内存大小
- Revit secondary development Hof method calls transaction
- MySQL uninstallation and installation methods
猜你喜欢
![[embedded] cortex m4f DSP Library](/img/83/ab421d5cc18e907056ec2bdaeb7d5c.png)
[embedded] cortex m4f DSP Library

Generator parameters incoming parameters

Restful API design specification

Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges

View computer devices in LAN

After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF

Computer graduation design PHP Zhiduo online learning platform

多元聚类分析

UML圖記憶技巧

Unsupported operation exception
随机推荐
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
Deep analysis of C language data storage in memory
LeetCode:673. 最长递增子序列的个数
What is the role of automated testing frameworks? Shanghai professional third-party software testing company Amway
The problem and possible causes of the robot's instantaneous return to the origin of the world coordinate during rviz simulation
Charging interface docking tutorial of enterprise and micro service provider platform
Mongodb installation and basic operation
R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
The network model established by torch is displayed by torch viz
Double pointeur en langage C - - modèle classique
【嵌入式】使用JLINK RTT打印log
Navicat Premium 创建MySql 创建存储过程
Revit secondary development Hof method calls transaction
Super efficient! The secret of swagger Yapi
vb.net 随窗口改变,缩放控件大小以及保持相对位置
【嵌入式】Cortex M4F DSP库
Computer cleaning, deleted system files
【ROS】usb_ Cam camera calibration
[today in history] February 13: the father of transistors was born The 20th anniversary of net; Agile software development manifesto was born
Crash problem of Chrome browser