二叉树的边界遍历指的是按照以下顺序遍历二叉树的节点:
以下是二叉树边界遍历的递归实现:
pythonCopy codeclass TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def printLeftBoundary(root): if root is None: return if root.left is not None: print(root.val, end=' ') printLeftBoundary(root.left) elif root.right is not None: print(root.val, end=' ') printLeftBoundary(root.right) def printRightBoundary(root): if root is None: return if root.right is not None: printRightBoundary(root.right) print(root.val, end=' ') elif root.left is not None: printRightBoundary(root.left) print(root.val, end=' ') def printLeaves(root): if root is None: return printLeaves(root.left) if root.left is None and root.right is None: print(root.val, end=' ') printLeaves(root.right) def printBoundary(root): if root is None: return print(root.val, end=' ') printLeftBoundary(root.left) printLeaves(root.left) printLeaves(root.right) printRightBoundary(root.right)
上述代码中,printLeftBoundary() 函数遍历左子树的左边界,不包括叶子节点;printRightBoundary() 函数遍历右子树的右边界,不包括叶子节点;printLeaves() 函数遍历树的叶子节点;printBoundary() 函数按照边界遍历的顺序输出节点。注意在输出叶子节点时,需要先输出左子树的叶子节点,再输出右子树的叶子节点。
printLeftBoundary()
printRightBoundary()
printLeaves()
printBoundary()
原文链接:codingdict.net