From ec09f22df47b904bbd38c3e8e9ba234acc679f2c Mon Sep 17 00:00:00 2001 From: ranwenjie Date: Mon, 15 Nov 2021 01:29:08 +0800 Subject: [PATCH] update tree --- 8 Algorithms Analysis/递归.md | 31 +++++++++++++------------- 9 Algorithms Job Interview/7 二叉树.md | 20 +++++++++++++++++ 2 files changed, 35 insertions(+), 16 deletions(-) diff --git a/8 Algorithms Analysis/递归.md b/8 Algorithms Analysis/递归.md index 0374c7f..761ed1e 100644 --- a/8 Algorithms Analysis/递归.md +++ b/8 Algorithms Analysis/递归.md @@ -232,25 +232,24 @@ public static LinkedNode mergeSeqLink(LinkedNode l1, LinkedNode l2){ ```Java - TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - // base case - if (root == null) return null; - if (root == p || root == q) return root; + // base case + if (root == null) return null; + if (root == p || root == q) return root; - TreeNode left = lowestCommonAncestor(root.left, p, q); - TreeNode right = lowestCommonAncestor(root.right, p, q); - // 情况 1 - if (left != null && right != null) { - return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + // 情况 1 :p, q 在 root 为根的树中 + if (left != null && right != null) { + return root; + } + // 情况 2 :p, q 不在 在 root 为根的树中 + if (left == null && right == null) { + return null; + } + // 情况 3 : p, q 只有1个在root 为根的树中 + return left == null ? right : left; } - // 情况 2 - if (left == null && right == null) { - return null; - } - // 情况 3 - return left == null ? right : left; -} ``` diff --git a/9 Algorithms Job Interview/7 二叉树.md b/9 Algorithms Job Interview/7 二叉树.md index 58bac03..28bcff2 100644 --- a/9 Algorithms Job Interview/7 二叉树.md +++ b/9 Algorithms Job Interview/7 二叉树.md @@ -117,6 +117,26 @@ TreeNode invertTree(TreeNode root) { 分析:求数中两个结点的最低共同结点是面试中经常出现的一个问题。这个问题至少有两个变种。 +``` +TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + // base case + if (root == null) return null; + if (root == p || root == q) return root; + + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + // 情况 1 :p, q 在 root 为根的树中 + if (left != null && right != null) { + return root; + } + // 情况 2 :p, q 不在 在 root 为根的树中 + if (left == null && right == null) { + return null; + } + // 情况 3 : p, q 只有1个在root 为根的树中 + return left == null ? right : left; + } +```