所谓树的结点的祖先指的是从根节点到达该节点所经过的结点,及该结点的父结点及系列父结点。使用递归的思想,也可以使用判断,入队的非递归思想,本例直接采用递归方式解决对于树这种数据结构而言,递归是一种非常使用的解决问题的方式。
/**
*@Title: Ancestors.java
*@Package binarytree
*@Description: 对于一颗普通的二叉树和一个节点key,找出该节点的所有祖先节点。
*@author peidong
*@date 2017-4-27 上午8:31:01
*@version V1.0
*/
/*使用递归的思想,也可以使用判断,入队的非递归思想,本例直接采用递归方式解决
对于树这种数据结构而言,递归是一种非常使用的解决问题的方式*/
packagebinarytree;
importbinarytree.ListToTree.TreeNode;
/**
* @ClassName: Ancestors
* @Description: TODO
* @date 2017-4-27 上午8:31:01
*
*/
publicclass Ancestors {
/**
*
* @ClassName: TreeNode
* @Description: 构建树节点
* @date 2017-4-27 上午8:32:10
*
*/
public static class TreeNode{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data){
this.data = data;
left = null;
right = null;
}
}
/**
*
* @Title: printAncestors
* @Description: 判断数据是否在树中,在则输出所有祖先结点数据
* @param @param root
* @param @param data
* @param @return
* @return boolean
* @throws
*/
public static booleanprintAncestors(TreeNode root, int data){
//边界条件
if(root == null){
return false;
}
//如果根节点即数据
if(root.data == data){
return true;
}
//遍历左右子树,存在的话,父结点即祖先
if(printAncestors(root.left, data)|| printAncestors(root.right, data)){
System.out.print(root.data+" ");
return true;
}
//不存在
return false;
}
/**
*@Title: main
*@Description: 测试案例
*@param @param args
*@return void
*@throws
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.left.left.left = newTreeNode(7);
//输出指定数据的祖先
printAncestors(root, 7);
}
}