236. Lowest common ancestor
236_solution1.c
#include "tree_node.h"
// LCA of a plain Binary Tree: recursive DFS, O(n) time, O(h) space
struct TreeNode *lowestCommonAncestor(struct TreeNode *root, struct TreeNode *p,
struct TreeNode *q) {
if (!root || 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; // p and q on different sides
return left ? left : right; // pass up whatever was found
}
tree_node.h
#pragma once
#include <stddef.h>
// Definition for a binary tree node.
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
236_solution1.cpp
#include "tree_node.h"
using namespace std;
class Solution {
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
if (!root || root == p || root == q)
return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if (left && right)
return root; // p and q on different sides
return left ? left : right; // pass up whatever was found
}
};
tree_node.h
#pragma once
// Definition for a binary tree node.
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) {}
};
236_solution1.go
package trees
// LCA of a plain Binary Tree: recursive DFS, O(n) time, O(h) space
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || root == p || root == q {
return root
}
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
if left != nil && right != nil {
return root // p and q on different sides
}
if left != nil {
return left // pass up whatever was found
}
return right
}
tree_node.go
package trees
// Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
236_solution1.java
// LCA of a plain Binary Tree: recursive DFS, O(n) time, O(h) space
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q)
return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null)
return root; // p and q on different sides
return left != null ? left : right; // pass up whatever was found
}
}
TreeNode.java
// Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
236_solution1.js
const TreeNode = require("./tree_node");
// LCA of a plain Binary Tree: recursive DFS, O(n) time, O(h) space
var lowestCommonAncestor = function (root, p, q) {
if (!root || root === p || root === q) return root;
const left = lowestCommonAncestor(root.left, p, q);
const right = lowestCommonAncestor(root.right, p, q);
if (left && right) return root; // p and q on different sides
return left ?? right; // pass up whatever was found
};
tree_node.js
// Definition for a binary tree node.
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
module.exports = TreeNode;
236_solution1.py
from tree_node import TreeNode
# LCA of a plain Binary Tree: recursive DFS, O(n) time, O(h) space
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root is p or root is q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root # p and q on different sides
return left or right # pass up whatever was found
tree_node.py
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
236_solution1.rs
use std::cell::RefCell;
use std::rc::Rc;
use crate::tree_node::TreeNode;
type Node = Option<Rc<RefCell<TreeNode>>>;
// LCA of a plain Binary Tree: recursive DFS, O(n) time, O(h) space
impl Solution {
pub fn lowest_common_ancestor(root: Node, p: Node, q: Node) -> Node {
let (p, q) = (p?, q?);
Self::dfs(root, &p, &q)
}
fn dfs(root: Node, p: &Rc<RefCell<TreeNode>>, q: &Rc<RefCell<TreeNode>>) -> Node {
let node = root?;
if Rc::ptr_eq(&node, p) || Rc::ptr_eq(&node, q) {
return Some(node);
}
let left = Self::dfs(node.borrow().left.clone(), p, q);
let right = Self::dfs(node.borrow().right.clone(), p, q);
match (left, right) {
(Some(_), Some(_)) => Some(node), // p and q on different sides
(l, r) => l.or(r), // pass up whatever was found
}
}
}
tree_node.rs
use std::cell::RefCell;
use std::rc::Rc;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}