博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据结构——查找二叉树已知节点的祖先节点
阅读量:4099 次
发布时间:2019-05-25

本文共 1837 字,大约阅读时间需要 6 分钟。

原文地址:

已知一个二叉树和一个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是已知二叉树中节点的数目。

转载地址:http://zuhii.baihongyu.com/

你可能感兴趣的文章
7 年工作经验,面试官竟然还让我写算法题???
查看>>
被 Zoom 逼疯的歪果仁,造出了视频会议机器人,同事已笑疯丨开源
查看>>
上古语言从入门到精通:COBOL 教程登上 GitHub 热榜
查看>>
再见,Eclipse...
查看>>
超全汇总!B 站上有哪些值得学习的 AI 课程...
查看>>
如果你还不了解 RTC,那我强烈建议你看看这个!
查看>>
神器面世:让你快速在 iOS 设备上安装 Windows、Linux 等操作系统!
查看>>
沙雕程序员在无聊的时候,都搞出了哪些好玩的小玩意...
查看>>
太赞了!GitHub 标星 2.4k+,《可解释机器学习》中文版正式开放!
查看>>
程序员用 AI 修复百年前的老北京视频后,火了!
查看>>
漫话:为什么你下载小电影的时候进度总是卡在 99% 就不动了?
查看>>
我去!原来大神都是这样玩转「多线程与高并发」的...
查看>>
当你无聊时,可以玩玩 GitHub 上这个开源项目...
查看>>
B 站爆红的数学视频,竟是用这个 Python 开源项目做的!
查看>>
安利 10 个让你爽到爆的 IDEA 必备插件!
查看>>
自学编程的八大误区!克服它!
查看>>
GitHub 上的一个开源项目,可快速生成一款属于自己的手写字体!
查看>>
早知道这些免费 API,我就可以不用到处爬数据了!
查看>>
Java各种集合类的合并(数组、List、Set、Map)
查看>>
JS中各种数组遍历方式的性能对比
查看>>