LCA-最近公共祖先
方法一、dfs
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode res; public Solution() { //构造函数 this.res = null; } public boolean dfs(TreeNode root, TreeNode p, TreeNode q) { if(root == null) return false; boolean lson = dfs(root.left, p, q); //深搜,先在左子树里找; boolean rson = dfs(root.right, p, q); //深搜,再在右子树里找 if((lson && rson) || ((root.val == p.val || root.val == q.val) && (lson || rson))) { res = root; } return lson || rson || (root.val == p.val || root.val == q.val);//返回的结果表示,当前节点的子树(包括节点本身)是否包含p或者q } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { this.dfs(root, p, q); return this.res; } }
方法二、HashMap
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /*所有节点的值都是唯一的 * LCA 求最近公共祖先 * 先从根节点遍历二叉树,存储每个节点的父亲节点的信息 * 然后从p出发,用vis记录其祖先 * 最后从q出发,判断vis中是否也包含q的祖先,如果有直接返回答案,返回的结果就是最近的公共祖先 * */ class Solution { Map<Integer, TreeNode> par = new HashMap<>(); Set<Integer> vis = new HashSet<>(); public void dfs(TreeNode root) { //dfs存储每个节点的父亲节点的信息 if(root.left != null) { par.put(root.left.val, root); dfs(root.left); } if(root.right != null) { par.put(root.right.val, root); dfs(root.right); } } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { dfs(root); while(p != null) { vis.add(p.val); p = par.get(p.val); } while(q != null) { if(vis.contains(q.val)) { return q; } q = par.get(q.val); } return null; } }
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!