leetcode 236. Lowest Common Ancestor of a Binary Tree | 236. 二叉树的最近公共祖先(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 236. Lowest Common Ancestor of a Binary Tree | 236. 二叉树的最近公共祖先(Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
題解
思路來源:左程云《程序員代碼面試指南》
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if (root == null || root == p || root == q) return root;TreeNode l = lowestCommonAncestor(root.left, p, q);TreeNode r = lowestCommonAncestor(root.right, p, q);if (l != null && r != null) return root;else if (r != null) return r;else return l;} }總結
以上是生活随笔為你收集整理的leetcode 236. Lowest Common Ancestor of a Binary Tree | 236. 二叉树的最近公共祖先(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 230. Kth Sm
- 下一篇: leetcode 238. Produc