查找二叉树任意两个节点的父节点

做一个容器,我们在遍历二叉树寻找节点的同时,把从根到节点的路径扔进去(两个节点就是两个容器)。由于根节点最后一个被扔进去,但我们接下来又需要第一个就能访问到它——后进先出,所以这个容器是一个栈。时间复杂度O(N),空间复杂度O(N)。

代码

public class BinNode
{
     public int Element;
     public BinNode Left;
     public BinNode Right;
     public BinNode(int element, BinNode left, BinNode right)
     {
         this.Element = element;
         this.Left = left;
         this.Right = right;
     }

static bool GetPositionByNode(BinNode root, BinNode node, ref Stack stack)
{
     if (root == null)
         return false;
     if (root == node)
     {
         stack.Push(root);
         return true;
     }
     if (GetPositionByNode(root.Left, node, ref stack) || GetPositionByNode(root.Right, node, ref stack))
     {
         stack.Push(root);
         return true;
     }
     return false;
}

然后我们要同时弹出这两个容器的元素,直到它们不相等,那么之前那个相等的元素就是我们要求的父亲节点。

代码

static BinNode FindParentNode(BinNode root, BinNode node1, BinNode node2)
{
     Stack stack1 = new Stack();
     GetPositionByNode(root, node1, ref stack1);
     Stack stack2 = new Stack();
     GetPositionByNode(root, node2, ref stack2);
     BinNode tempNode = null;
     while (stack1.Peek() == stack2.Peek())
     {
         tempNode = (BinNode)stack1.Pop();
         stack2.Pop();
     }
     return tempNode;
}

posted @ 2014-04-11 13:50  蜗牛超悍马  阅读(1388)  评论(0编辑  收藏  举报