沿着右子树找,不存在两个子树都能够找到。
代码:
struct TreeNode {<pre name="code" class="html">struct TreeNode { int data; TreeNode* leftChild; TreeNode* rightChild; TreeNode* parent; }; //用父结点 bool findNearestAncestor2(const TreeNode* vNodeA, const TreeNode* vNodeB, TreeNode *vAncestor) { if (isFather(vNodeA, vNodeB)) { vAncestor = vNodeA; return true; } if (isFather(vNodeB, vNodeA)) { vAncestor = vNodeB; return true; } TreeNode* Parent = vNodeA->parent; while (true) { if (isFather(Parent, vNodeB)) { vAncestor = Parent; return true; } Parent = Parent->parent; } return false; }
在看第二种情况比较简单,如果有指向父结点的指针,我们可以搜索第一个结点的
父节点,然后判断是不是第二个已知结点的父结点。
代码:
struct TreeNode { int data; TreeNode* leftChild; TreeNode* rightChild; TreeNode* parent; }; //用父结点 bool findNearestAncestor2(const TreeNode* vNodeA, const TreeNode* vNodeB, TreeNode *vAncestor) { if (isFather(vNodeA, vNodeB)) { vAncestor = vNodeA; return true; } if (isFather(vNodeB, vNodeA)) { vAncestor = vNodeB; return true; } TreeNode* Parent = vNodeA->parent; while (true) { if (isFather(Parent, vNodeB)) { vAncestor = Parent; return true; } Parent = Parent->parent; } return false; }
019写程序在一棵二叉树中找到两个结点的最近共同祖先(keep it up)
原文地址:http://blog.csdn.net/xiaoliangsky/article/details/39110457