Recursion on Tree

Recursion on Tree
Q: for each node in a tree, store the number of nodes in its left child subtree
  • way of thinking:
  1. what do you expect from your leaf child/ right child?
    total number of nodes in my left subtree
    total number of nodes in my right subtree
  2. what do you want to do in the current layer?
    store the number of nodes in the left subtree
  3. what do you want to return to your parent?
    same as number 1
def chang_subtree(node):
  if node is None:
    return 0
  left_total = change_subtree(node.left)
  right_total = change_subtree(node.right)
  node.total_left = left_total
  return 1 + left_total + right+total
Q: Find the node with the max difference in the total number of descendents in its left subtree and right subtree.
  • way of thinking:
  1. what do you expect from your leaf child/ right child?
    total number of nodes in my left subtree
    total number of nodes in my right subtree
  2. what do you want to do in the current layer?
    diff = abs(left_total - right_total)
    global_max_diff = max(diff, global_max_diff)
  3. what do you want to return to your parent?
    return 1 + left_total + right_total
global_max = -1
res = None

def node_diff(root):
  if root is None:
    return 0
  left_total = node_diff(root.left)
  right_total = node_diff(root.right)
  global global_max
  global res
  if abs(left_total - right_total) > global_max:
    global_max = abs(left_total - right_total)
    res = root
  return left_total + right_total + 1
Generally, choose root is None as base case. But sometimes, if we need something related to leaf, we need to choose leaf node( root.left is None and root.rightis None) as base case.
Q: Given a binary tree, find its minimum depth.
def minHeight(root):
  if root is None: #edge case
    return 0
  if root.left is None and root.right is None #base case
    return 1
#此处必须选他作为base case否则只有一个孩子的node会返回0
  left = minHeight(root.left) if root.left else float('inf') #infinity
  right = minHeight(root.right) if root.right else float('inf')
  return min(left, right) + 1
Q: Given a binary tree, write a function to determine whether this tree is a binary search tree
def BST(root): #这个function在这里有global的意味
  if root is None:
    return True
  min = float('-inf')
  max = float('inf')
  return isBST(root, min, max)

def isBST(root, min, max): #check the order of the values in the tree
  if root is None:
    return True
  if roo.val <= min or root.val >= max:
    return False
  return isBST(root.left, min, root.val) and isBST(root.right, root.val, max)

other ideas
a. use inorder traversal

#储存当前上一个节点的value到prev中,看它是不是比当前value小。对于root,prev node是left, 对于right,prev node是root。所以recursion中先找left,执行inorder left,存入prev,比较它与当前value,然后存当前value于prev中,执行inorder right
def is ValidBST(root):
  prev = [None]
  res = [True]
  inorder(root, prev, res)
  return res[0]
def inorder(root, prev, res):
  if not root:
    return
  inorder(root.left, prev, res)
  if prev[0] and prev[0] >= root.val:
    res[0] = False
  prev[0] = root.val
  inorder(root.right, prev, res)

b.

  • way of thinking:
  1. what do you expect from your leaf child/ right child?
    left_res: 左子树是否为BST/左子树最大值/左子树最小值
    right_res: 右子树是否为BST/右子树最大值/右子树最小值
  2. what do you want to do in the current layer?
    isBST = left_res.isBST and right_res.isBST and lef_res.max < root.val and right_res.min > root.val
  3. what do you want to return to your parent?
    return (isBST, left_res.min or root.val, right_res.max or root.val)
# in python: 12 or 25 = 12
#                  12 and 25 = 25
# if 25 == if True 和c++用法相同

def isBSTHelper(root):
  if not root:
    return (True, None, None)
  left_res = isBSTHelper(root.left)
  right_res = isBSTHelper(root.right)
  if not left_res[0] or not right_res[0]:
    return (False, None, None)
  if left_res[2] and root.val <= left_res[2]:
    return (False, None, None)
  if right_res[1] and root.val >= right.res[1]:
    return (False, None, None)
  return (True, left_res[1] or root.val, right_res[2] or root.val)
Q: Find the lowest Common Children
  • way of thinking:
  1. what do you expect from your leaf child/ right child?
    LCA found in the children
  2. what do you want to do in the current layer?
    case 1: LCA found in both cases -> current root is LCA
    case 2: LCA found ar one side of children -> LCA found in the children
  3. what do you want to return to your parent?
    LCA found in the children
def LCA(root, p, q)
  if not root:
    return None
  if root == p or root == q:
    return root
  left_res = LCA(root.left, p, q)
  right_res = LCA(root.right, p, q)
  if left_LCA and right_LCA:
    return root
  else if left_res:
    return left_res
  else:
    return right_res
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,269评论 0 10
  • 一转眼,春天到了,准备好心态,出发。
    义哥0128阅读 150评论 0 0
  • 生活在油盐酱醋中,一天,老婆突然赞许地说:好像我们已经很久没有吵架了。我突然惊觉,我已经想不起上次吵架是什么时候,...
    蔷薇睥睨阅读 510评论 0 6
  • 多想 多想 多想 抱抱你 多想 多想 多想 看着你 也许我们就应该再也不见 哪怕有一天偶然的擦肩而过 我们的距离皱...
    爱上王子的丑小鸭阅读 111评论 0 1
  • 今天在去往图书馆的路上,想到了他。很奇怪,这个明明在我心中都算是翻篇的人物,却不自觉地出现在我的脑海中。 有关于他...
    笑笑_feng阅读 405评论 0 1