236. Lowest Common Ancestor of a 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.

题目含义:求一个普通二叉树中两个节点的最小公共父节点

1     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
2         if (root == null || p == root || q == root) return root;
3         TreeNode left = lowestCommonAncestor(root.left, p, q);
4         TreeNode right = lowestCommonAncestor(root.right, p , q);
5         if (left!=null && right!=null) return root;  //p和q与root的左右子节点相等,那么root即为p和q的公共父节点
6         return left!=null ? left : right;//p和q至少有一个为空,表示p和q落在了root的同一侧子树中,所以应该返回不为空的那个子树节点     
7     }

 类似题目:235. Lowest Common Ancestor of a Binary Search Tree

原文地址:https://www.cnblogs.com/wzj4858/p/7712128.html