用C语言编写查找中序遍历的最后一个节点
时间: 2024-02-18 19:32:04 浏览: 65
C语言实现二叉排序树构造 查找删除节点 中序遍历
5星 · 资源好评率100%
假设你已经实现了一个二叉树的中序遍历函数`inorder_traversal()`,那么查找中序遍历的最后一个节点的C语言代码如下所示:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* inorder_traversal(struct TreeNode* root, struct TreeNode* prev) {
if (root == NULL) return prev;
prev = inorder_traversal(root->left, prev);
prev = root;
prev = inorder_traversal(root->right, prev);
return prev;
}
struct TreeNode* last_inorder_node(struct TreeNode* root) {
return inorder_traversal(root, NULL);
}
```
这段代码中,我们定义了一个`struct TreeNode`结构体表示二叉树节点,其中包含节点的值`val`、左子树指针`left`和右子树指针`right`。`inorder_traversal()`函数是递归实现的中序遍历函数,它接受两个参数:当前节点`root`和前一个遍历到的节点`prev`,并返回遍历到的最后一个节点。在递归过程中,我们先遍历左子树,然后将当前节点`root`赋值给`prev`,最后遍历右子树。`last_inorder_node()`函数是查找中序遍历的最后一个节点的函数,它调用了`inorder_traversal()`函数,将初始的前一个节点`prev`设置为`NULL`。最后,`last_inorder_node()`函数返回遍历到的最后一个节点。
使用示例:
```c
int main() {
struct TreeNode n1 = {1, NULL, NULL};
struct TreeNode n2 = {2, NULL, NULL};
struct TreeNode n3 = {3, NULL, NULL};
struct TreeNode n4 = {4, NULL, NULL};
struct TreeNode n5 = {5, NULL, NULL};
struct TreeNode n6 = {6, NULL, NULL};
struct TreeNode n7 = {7, NULL, NULL};
struct TreeNode n8 = {8, NULL, NULL};
struct TreeNode n9 = {9, NULL, NULL};
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
n3.left = &n6;
n3.right = &n7;
n4.left = &n8;
n4.right = &n9;
struct TreeNode* last_node = last_inorder_node(&n1);
printf("%d\n", last_node->val);
return 0;
}
```
输出结果为:
```
9
```
阅读全文