1. 程式人生 > >LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)

LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)

java text track ron 代碼 eno turn javascrip pan

Lowest Common Ancestor of a Binary Search Tree

一、題目描寫敘述

技術分享

二、思路及代碼

二叉搜索樹有個性質:左子樹的值都比根節點小,右子樹的值比根節點大。那麽我們的思路就是遞歸比較。
假設輸入的兩個節點的值比當前節點小,說明是在當前根節點的左子樹中;反之則在右子樹中。

假設當前根節點比一個大。比一個小。那麽第一個出現的這種節點就是近期的父親節點了。

/**
 * 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.val > p.val && root.val > q.val){ return lowestCommonAncestor(root.left, p, q); }else if(root.val < p.val && root.val < q.val){ return
lowestCommonAncestor(root.right, p, q); }else{ return root; } } }

Lowest Common Ancestor of a Binary Tree

一、題目描寫敘述

技術分享

二、思路及代碼

假設是普通的二叉樹。沒有了二叉搜索樹的特性。就要遍歷;於是我們用到DFS遍歷樹

/**
 * 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 || root == p || root == q) return root; //找到p或者q節點,或者到最底層的葉子節點時,返回; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) return root; //找到了父節點 return left != null ?

left : right; //所以假設都未找到,返回null } }

LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)