阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1. Tree traverse
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None1.1 pre-order
def preorder(root):
# base case
if not root:
return
# recursion rule
print(root.val)
preorder(root.left)
preorder(root.right)1.2 in-order
def inorder(root):
# base case
if not root:
return
# recursion rule
inorder(root.left)
print(root.val)
inorder(root.right)1.3 past-order
def pastorder(root):
# base case
if not root:
return
# recursion rule
pastorder(root.left)
pastorder(root.right)
print(root.val)2. 几种常见的Binary Tree类型
2.1 Balanced binary tree(平衡二叉树)
The depth of the left and right subtrees of every node differ by 1 or less.
平衡性例子: [10,5,15,2,7,12,20]各节点左右子树高度差≤1,是高度平衡树;只向右延长为10→15→20时根的高度差为2,不平衡。必须逐节点检查,不只比较根的高度。
2.2 Completed binary tree(完全二叉树)
Every level, except possibly the last, is completely filled, and all nodes are as far left as possible.
完全性例子: 层序[10,5,15,2,7,12]最后一层从左连续填充,是完全二叉树;若缺少12却仍有最右的20,会出现空洞而不完全。完全树可用数组的2i+1、2i+2关系寻址。
2.3 Binary search tree(二叉搜索树)
For BST, in-order traversal will form an ascending order.
BST例子: 根10、左5(子2和7)、右15(子12和20),中序为2,5,7,10,12,15,20。若把左子树的7改成11,即使父子局部看似有序,也违反左子树全部小于根10的要求。
3. Practice
3.1 Get height of a BT
def get_height(root):
# base case
if not root:
return 0
left_height = get_height(root.left)
right_height = get_height(root.right)
return max(left_height, right_height) + 13.2 Print the binary tree in the level order
层序独立示意: 根10;第二层5、15;第三层2、7、12、20。队列按先入先出逐层输出,下一段测试构造使用同一组节点。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = Nonefrom collections import deque
def level(root):
q = deque([root])
next = deque()
line = deque()
while q:
head = q.popleft()
if head.left:
next.append(head.left)
if head.right:
next.append(head.right)
line.append(head.val)
if not q:
print(line)
if next:
q = next
next = deque()
line = deque()# Test case
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(2)
root.left.right = TreeNode(7)
root.right.left = TreeNode(12)
root.right.right = TreeNode(20)
level(root)deque([10])
deque([5, 15])
deque([2, 7, 12, 20])
3.2 Flip tree
Given a BT where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
翻转前后: 原树1(left=2,right=3)、2(left=4,right=5);翻转后根为4,4(left=5,right=2)、2(left=3,right=1)。原右节点均为有左兄弟的叶节点,符合题目前提。
->
翻转指针规则: 递归先翻转左子树,再令原left.left=原right、原left.right=原root,清空原root.left/right。图中的局部变换与下方代码逐句对应。
def upside_tree(root):
if not root:
return root
if not root.left and not root.right:
return root
new_root = upside_tree(root.left)
root.left.left = root.right
root.left.right = root
root.left = None
root.right = None
return new_root