数据结构——查找二叉树已知节点的祖先节点
2016-12-03 16:44
405 查看
原文地址:Print Ancestors of a given node in Binary Tree
已知一个二叉树和一个key,写一个函数打印出这个二叉树中已知节点的所有祖先节点。
例如:如果已知的树是下面的二叉树,而且key是7,然后你的function应该打印出4,2和1。
输出:
时间复杂度是:O(n),在这里n是已知二叉树中节点的数目。
已知一个二叉树和一个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是已知二叉树中节点的数目。
相关文章推荐
- 【数据结构与算法】求二叉树中两个节点的最近祖先
- 数据结构之查找二叉树
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 利用栈结构实现二叉树的非递归遍历,求二叉树深度、叶子节点数、两个结点的最近公共祖先及二叉树结点的最大距离
- 利用栈结构实现二叉树的非递归遍历,求二叉树深度、叶子节点数、两个结点的最近公共祖先及二叉树结点的最大距离
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构之查找二叉树
- 二叉树——查找两个随机节点最近的祖先
- 二叉树(12)----查找两个节点最低祖先节点(或近期公共父节点等),递归和非递归
- 利用栈结构实现二叉树的非递归遍历,求二叉树深度、叶子节点数、两个结点的最近公共祖先及二叉树结点的最大距离
- 二叉树——查找两个任意节点的最近祖先
- 查找二叉树某两个节点最近的共同祖先及改进方法
- 【数据结构与算法】二叉树给定两个节点的最短距离(C++实现)
- 在二叉树中查找两个节点的最近的公共祖先节点(无回溯指针)(NCA--nearest common ancestor)
- 二叉树中查找两个节点的最低公共祖先
- 数据结构之查找二叉树--BST
- Java 数据结构之一般树形结构中父节点和子节点的查找
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(一)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现