tag: 二叉树
思路一: 分治
思路二:非递归???
package com.zhaochao.tree; /** * Created by zhaochao on 17/1/24. * lowest common ancestor */ public class LCA { // 在root为根的二叉树中找A,B的LCA: // 如果找到了就返回这个LCA // 如果只碰到A,就返回A // 如果只碰到B,就返回B // 如果都没有,就返回null public TreeNode LCARec(TreeNode root, TreeNode rootA, TreeNode rootB) { if(root == null || root == rootA || root == rootB) { return root; } TreeNode left = LCARec(root.left, rootA, rootB); TreeNode right = LCARec(root.right, rootA,rootB); if(left != null && right != null) { return root; } if(left != null) { return left; } if(right != null) { return right; } return null; } }
时间: 2024-10-09 18:17:28