【Leetcode】Lowest common treenode in binary tree

【題目】

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.

 

【思路】

方法一:

這道題和BST相似,但不如那個容易解決,因爲沒有BST的性質。

use a map to save the node and its parent,then use this map to form the route of p,finally let the q goes up when it touches the route.

用map先把每個節點的根節點記錄下來,遍歷tree的方法用的是BFS。所以要加一個queue;

都存下來以後。根據這個map獲得p的路徑,將p的所有祖先放在set裏面。

然後在用q 的根進行檢測。如果有就是了~

【代碼】

public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    HashMap<TreeNode,TreeNode> m = new HashMap<TreeNode,TreeNode>();
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while(queue.peek()!=null){
        TreeNode t = queue.poll();
        if(t.left!=null){
            m.put(t.left,t);
            queue.offer(t.left);
        }
        if(t.right!=null){
            m.put(t.right,t);
            queue.offer(t.right);
        }
    }
    Set<TreeNode> l = new HashSet<TreeNode>();
    TreeNode pp = p;
    while(pp!=root){
        l.add(pp);
        pp = m.get(pp);
    }
    l.add(root);
    TreeNode qq = q;
    while(!l.contains(qq)){
        qq = m.get(qq);
    }
    return qq;
}

方法二;



Just blind try left and right. Then if we find in both left and right side return root, otherwise return the one we got.


  if (root == p || root == q || root == null) { return root; }
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    return (left != null && right != null) ? root : (left != null ? left : right);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章