LeetCode Lowest Common Ancestor of a Binary Tree

原题链接在这里:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

题目:

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

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

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

题解:

Lowest Common Ancestor of a Binary Search Tree进阶题目。

无法比较大小,但是可以看p,q是不是在root的两边,若在两边,left 和 right 同时不失null, 则返回root.

若都在一边,比如left, 就在left边继续。

Note:1. 若有root == p || root == q时,需比较原来的点而不单单是val, 这里可以有重复的值,在能比较整体点时就不比较val.

2. 递归终止条件这里有两个,一个是root == null, 一个是root等于p或者q, 这两个终止条件缺一不可。

Time Complexity: O(n), 每个点没有traverse超过两遍. Space: O(logn), 是树的高度。

AC Java:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null){
return root;
}
if(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;
}else if(left != null){
return left;
}else{
return right;
}
}
}

跟上Smallest Subtree with all the Deepest Nodes.

类似Smallest Common Region.

上一篇:Centos7最小化安装


下一篇:centos系统设置局域网静态IP