首页 > 其他分享 >计算思维的门槛:递归思想

计算思维的门槛:递归思想

时间:2023-02-16 20:34:02浏览次数:49  
标签:思维 right TreeNode 递归 门槛 return null root left

今天做题发现了一道对递归最佳辅助理解的题目:剑指 Offer 68 - II. 二叉树的最近公共祖先,二叉树对理解递归的帮助很大。

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12         if (root == null || root == p || root == q) {
13             return root;
14         }
15         TreeNode left = lowestCommonAncestor(root.left, p, q);
16         TreeNode right = lowestCommonAncestor(root.right, p, q);
17         if (left == null && right == null) {
18             return null;
19         }
20         if (left == null) {
21             return right;
22         }
23         if (right == null) {
24             return left;
25         }
26         return root;
27     }
28 }

 

 

标签:思维,right,TreeNode,递归,门槛,return,null,root,left
From: https://www.cnblogs.com/RQfreefly/p/17128192.html

相关文章