Leetcode:235. Lowest Common Ancestor of a Binary Search Tree(JAVA)

来源:互联网 发布:arcgis数据视图做表格 编辑:程序博客网 时间:2024/06/07 15:42

【问题描述】

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

【思路】

递归实现,如果p.val, q.val均小于root.val的话,搜索左子树,如果都大于的话,搜索右子树,否则为root

    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {            if (root == null || p == null || q == null) {return null;}        if (p.val < root.val && q.val < root.val) {return lowestCommonAncestor(root.left, p, q);}else if (Math.min(p.val, q.val)>root.val) {return lowestCommonAncestor(root.right, p, q);} else {return root;}    }

【思路2】

搜索到跟节点的路径,记录下,最后一个相同的节点即为搜索节点。

public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p,TreeNode q) {if (root == null || p == null || q == null) {return null;}List<TreeNode> ppath = new ArrayList<TreeNode>();List<TreeNode> qpath = new ArrayList<TreeNode>();ppath.add(root);qpath.add(root);getPath(root, p, ppath);getPath(root, q, qpath);TreeNode lca = null;for (int i = 0; i < ppath.size() && i < qpath.size(); i++) {if (ppath.get(i) == qpath.get(i)) {lca = ppath.get(i);}else {break;}}return lca;}private static boolean getPath(TreeNode root, TreeNode n,List<TreeNode> path) {if (root == n) {return true;}if (root.left != null) {path.add(root.left);if (getPath(root.left, n, path)) {return true;}path.remove(path.size() - 1);}if (root.right != null) {path.add(root.right);if (getPath(root.right, n, path)) {return true;}path.remove(path.size() - 1);}return false;}


0 0
原创粉丝点击