#! /usr/bin/env python import sys from tree_generate import get_tree max_num = -sys.maxint def f(r): global max_num if not r: return 0 left = f(r.left) right = f(r.right) max_num = max(r.value+max(left,right,left+right,0), max_num) return r.value + max(left,right,0) r = get_tree([3,9,20,'#','#',15,7]) f(r) print max_num
def f(r, target): if not r: return False s = [] s.append(r) prev = None res = [] while s: n = s[-1] if not prev or prev.left==n or prev.right==n: target -= n.value if n.left: s.append(n.left) elif n.right: s.append(n.right) elif not target: res.append(copy.deepcopy(s)) elif prev == n.left: if n.right: s.append(n.right) else: s.pop() target+=n.value prev = n for it in res: for it2 in it: print it2.value, print r = get_tree([5,4,8,11,'#',13,4,7,2,'#','#',5,1]) f(r,21)
#! /usr/bin/env python from treenode import treenode from tree_generate import get_tree from binary_tree_level_order_travelsal import f as print_tree def f(r): if not r: return s = [] s.append(r) prev = None while s: n = s.pop() if prev: prev.right = n prev = n if n.right: s.append(n.right) if n.left: s.append(n.left) n.left=None return r r = get_tree([5,0,-4,-1,-6,-9,'#',7,'#',1,3,'#',0,'#',9,'#','#',6,0,'#',-7,'#','#','#','#','#','#',-4,'#',1,'#','#',-4]) r = f(r) print_tree(r)
#! /usr/bin/env python from tree_generate import get_tree def f(r): if not r: return s = [] s.append(r) prev = None while s: n = s[-1] if not prev or prev.left == n or prev.right == n: if n.left: s.append(n.left) else: print n.value s.pop() if n.right: s.append(n.right) prev = n else: print n.value s.pop() if n.right: s.append(n.right) prev = n r = get_tree([1,2,5,3,4,'#',6]) f(r)