236. Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:什么是矩阵图片 编辑:程序博客网 时间:2024/06/16 02:53

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).”

        _______3______       /              \    ___5__          ___1__   /      \        /      \   6      _2       0       8         /  \         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Subscribe to see which companies asked this question

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private boolean search(TreeNode root,TreeNode p,List<TreeNode> ret){        if(root==null)return false;        ret.add(root);        if(root==p){            // ret.add(root.val);            return true;        }        if(search(root.left,p,ret)==true)return true;        if(search(root.right,p,ret)==true)return true;        ret.remove(ret.size()-1);        return false;    }    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        List<TreeNode> ret1 = new ArrayList<>();        List<TreeNode> ret2 = new ArrayList<>();        search(root,p,ret1);        search(root,q,ret2);        TreeNode ret = null;        int len = Math.min(ret1.size(),ret2.size());        for(int i = 0;i<len;++i){            if(ret1.get(i)==ret2.get(i))ret = ret1.get(i);            else break;        }        return ret;    }}

0 0
原创粉丝点击