请写出按先序次序建立一棵二叉树(二叉链表),然后输出先序遍历结果的第k个结点值的代码
时间: 2024-05-01 16:18:00 浏览: 110
C语言 求一个二叉树中位于先序序列中第k个位置的结点的值.doc
好的,我知道了。以下是按先序次序建立二叉树并输出先序遍历结果的第k个结点值的代码:
```python
class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def build_tree(vals):
if not vals:
return None
val = vals.pop(0)
if val == None:
return None
node = TreeNode(val)
node.left = build_tree(vals)
node.right = build_tree(vals)
return node
def pre_order_traversal(node):
if not node:
return
print(node.val, end=" ")
pre_order_traversal(node.left)
pre_order_traversal(node.right)
vals = [1, 2, None, 3, None, None, 4, None, 5]
root = build_tree(vals)
pre_order_traversal(root)
k = 3
count = 0
def kth_node(node):
global count
if not node:
return None
count += 1
if count == k:
return node.val
return kth_node(node.left) or kth_node(node.right)
print(kth_node(root))
```
以上代码按先序次序建立了一棵二叉树,然后输出了先序遍历结果,并计算并输出了先序遍历结果的第k个结点值。
阅读全文