求二叉树两结点的最近共同父结点,在网上看到了一个挺有意思的解法,原文在http://www.cnblogs.com/remlostime/archive/2012/11/26/2788795.html
一般思路是从子节点深度遍历到根节点,然后比较两个路径的分叉点。他用的递归:
1 struct Node 2 { 3 int val; 4 Node *left; 5 Node *right; 6 Node():left(NULL), right(NULL){} 7 }; 8 9 Node *findFather(Node *root, Node *node1, Node *node2, bool &node1Find, bool &node2Find) 10 { 11 if (root == NULL) 12 return NULL; 13 14 bool leftNode1Find = false, leftNode2Find = false; 15 Node *leftNode = findFather(root->left, node1, node2, leftNode1Find, leftNode2Find); 16 if (leftNode != NULL) 17 return leftNode; 18 19 bool rightNode1Find = false, rightNode2Find = false; 20 Node *rightNode = findFather(root->right, node1, node2, rightNode1Find, rightNode2Find); 21 if (rightNode != NULL) 22 return rightNode; 23 24 node1Find = leftNode1Find || rightNode1Find; 25 node2Find = leftNode2Find || rightNode2Find; 26 27 if (node1Find && node2Find) 28 return root; 29 30 if (root == node1) 31 node1Find = true; 32 33 if (root == node2) 34 node2Find = true; 35 36 return NULL; 37 }
时间: 2024-10-02 23:44:44