GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithms/tree/bst/kth_smallest.py at master · vspriya05/algorithms Expand file tree/ Copy pathkth_smallest.pyMore file actions 54 lines (46 loc) · 1.13 KB / Copy pathkth_smallest.pyFile metadata and controls54 lines (46 loc) · 1.13 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def kth_smallest(root, k): stack = [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() k -= 1 if k == 0: break root = root.right return root.val class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ count = [] self.helper(root, count) return count[k-1] def helper(self, node, count): if not node: return self.helper(node.left, count) count.append(node.val) self.helper(node.right, count) if __name__ == '__main__': n1 = Node(100) n2 = Node(50) n3 = Node(150) n4 = Node(25) n5 = Node(75) n6 = Node(125) n7 = Node(175) n1.left, n1.right = n2, n3 n2.left, n2.right = n4, n5 n3.left, n3.right = n6, n7 print(kth_smallest(n1, 2)) print(Solution().kthSmallest(n1, 2)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |