面试题6:二叉树最近公共节点(LCA)《leetcode236》
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).”
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.
给定一个二叉树和所要查找的两个节点,找到两个节点的最近公共父亲节点(LCA)。比如,节点5和1的LCA是3,节点5和4的LCA是5。
1 class Solution { 2 public: 3 TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode* p,TreeNode* q){ 4 if(root == nullptr || root == p || root == q){ 5 return root; 6 } 7 TreeNode* left = lowestCommonAncestor(root->left,p,q); 8 TreeNode* right = lowestCommonAncestor(root->right,p,q); 9 if(left && right) return root; 10 if(left == nullptr) return right; 11 if(right == nullptr) return left; 12 } 13 };