数据结构——查找二叉树已知节点的祖先节点

原文地址:Print Ancestors of a given node in Binary Tree

已知一个二叉树和一个key,写一个函数打印出这个二叉树中已知节点的所有祖先节点。

例如:如果已知的树是下面的二叉树,而且key是7,然后你的function应该打印出4,2和1。

              1
            /   \
          2      3
        /  \
      4     5
     /
    7
// Java program to print ancestors of given node

/* A binary tree node has data, pointer to left child
   and a pointer to right child */
class Node 
{
    int data;
    Node left, right, nextRight;

    Node(int item) 
    {
        data = item;
        left = right = nextRight = null;
    }
}

class BinaryTree 
{
    Node root;

    /* If target is present in tree, then prints the ancestors
       and returns true, otherwise returns false. */
    boolean printAncestors(Node node, int target) 
    {
         /* base cases */
        if (node == null)
            return false;

        if (node.data == target)
            return true;

        /* If target is present in either left or right subtree 
           of this node, then print this node */
        if (printAncestors(node.left, target)
                || printAncestors(node.right, target)) 
        {
            System.out.print(node.data + " ");
            return true;
        }

        /* Else return false */
        return false;
    }

    /* Driver program to test above functions */
    public static void main(String args[]) 
    {
        BinaryTree tree = new BinaryTree();

        /* Construct the following binary tree
                  1
                /   \
               2     3
              /  \
             4    5
            /
           7
        */
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.left.left.left = new Node(7);

        tree.printAncestors(tree.root, 7);

    }
}

// This code has been contributed by Mayank Jaiswal

输出:

4 2 1

时间复杂度是:O(n),在这里n是已知二叉树中节点的数目。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值