236. Lowest Common Ancestor of a Binary Tree
Posted 白天黑夜每日c
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了236. 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
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./** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { TreeNode node = null; public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { findNode(root, p, q); return node; } public int findNode(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return 0; } int re = 0; if (root == p) { re = 1 + findNode(root.left, p, q) + findNode(root.right, p, q); } else if (root == q) { re = 2 + findNode(root.left, p, q) + findNode(root.right, p, q); } else { int left = findNode(root.left, p, q); if (left == 3) { return 3; } int right = findNode(root.right, p, q); if (right == 3) { return 3; } re = left + right; } if (re == 3) { node = root; } return re; } }
recursively root,检查root是否是pq,root的左子树是否有pq,root的右子树是否有pq。 18%
**这种办法是基于p、q一定在root中
/** * 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 null; if(root==p || root==q) return root; TreeNode left=lowestCommonAncestor(root.left, p, q), right = lowestCommonAncestor(root.right, p, q); if(left!=null && right!=null) return root; if(right==null) return left; if(left==null) return right; return null; } }
以上是关于236. Lowest Common Ancestor of a Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 236. Lowest Common Ancestor of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree