[LeetCode]236. Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:pdf修改软件绿色版 编辑:程序博客网 时间:2024/05/16 12:16

Problem Description

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

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).”
[https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/]

思路

先把从根节点到两个结点的路径求出来,然后再后退选择最低的公共父节点
大神们的思路:迭代递归,如果root是所求,那么p和q一定在root的左右子树中。。好简单有没有!!摔!
[https://leetcode.com/discuss/45399/my-java-solution-which-is-easy-to-understand]

Code

package q236;import java.util.*;import TreeNode.*;public class Solution {    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        List<List<TreeNode>> path = new ArrayList<List<TreeNode>>();        List<TreeNode> tmp = new ArrayList<TreeNode>();        tmp.add(root);        helper(tmp, root, p, path);        helper(tmp, root, q, path);        for (int i = path.get(0).size() - 1; i >= 0; i--) {            for (int j = path.get(1).size() - 1; j >= 0; j--) {                if (path.get(0).get(i) == path.get(1).get(j))                    return path.get(0).get(i);            }        }        return null;    }    public void helper(List<TreeNode> path, TreeNode root, TreeNode target,            List<List<TreeNode>> ans) {        if (root == target) {            ans.add(new ArrayList<TreeNode>(path));            return;        } else {            if (root.left != null) {                path.add(root.left);                helper(path, root.left, target, ans);                path.remove(path.size() - 1);            }            if (root.right != null) {                path.add(root.right);                helper(path, root.right, target, ans);                path.remove(path.size() - 1);            }        }    }    // public static void main(String[] args) {    // Solution s = new Solution();    // Codec c = new Codec();    // TreeNode root = c    // .deserialize("6,2,8,0,4,7,9,null,null,3,5,null,null,null,null");    // TreeNode p = c.getNode(root, 2);    // TreeNode q = c.getNode(root, 8);    // // System.out.println(p.val);    // // System.out.println(q.val);    // TreeNode ans = s.lowestCommonAncestor(root, p, q);    // System.out.println(ans.val);    //    // }}
0 0
原创粉丝点击