二叉树中查找一个结点

在二叉树中查找一个结点

在二叉树中查找一个结点,如果找到返回结点地址,如果没找到,返回NULL

查找策略:优先左,如果是空树,返回NULL;如果查找的是根,直接返回根的地址,先去左子树中找,如果找到了,返回结果,如果左子树也没有找到,再去找右子树。

Node * Search(BNode *root, TDatatype key)
{
	if (root == NULL) {
		return NULL;
	}

	if (root->data == key) {
		// 如果根命中了
		return root;
	}

	BNode *node = Search(root->left, key);
	if (node != NULL) {
		// 左子树中找到了
		return node;
	}

	node = Search(root->right, key);
	if (node != NULL) {
		return node;
	}
	else {
		return NULL;
	}
}
以下是Java代码实现构造一颗三叉链表表示的二叉树,以及在二叉树查找一个结点的方法: ```java class TreeNode { int val; TreeNode left; TreeNode right; TreeNode parent; public TreeNode(int val) { this.val = val; this.left = null; this.right = null; this.parent = null; } } class ThreeLinkBinaryTree { private TreeNode root; public ThreeLinkBinaryTree() { this.root = null; } public void createTree(int[] arr) { for (int i = 0; i < arr.length; i++) { insert(arr[i]); } } private void insert(int val) { TreeNode newNode = new TreeNode(val); if (root == null) { root = newNode; } else { TreeNode current = root; TreeNode parent; while (true) { parent = current; if (val < current.val) { current = current.left; if (current == null) { parent.left = newNode; newNode.parent = parent; return; } } else { current = current.right; if (current == null) { parent.right = newNode; newNode.parent = parent; return; } } } } } public TreeNode findNode(int val) { TreeNode current = root; while (current != null && current.val != val) { if (val < current.val) { current = current.left; } else { current = current.right; } } return current; } } ``` 使用示例: ```java public static void main(String[] args) { int[] arr = { 5, 2, 8, 1, 4, 6, 9 }; ThreeLinkBinaryTree tree = new ThreeLinkBinaryTree(); tree.createTree(arr); TreeNode node = tree.findNode(4); if (node != null) { System.out.println("找到了节点:" + node.val); } else { System.out.println("未找到节点"); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值