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 — leetcode/tree/Yu/257.py at master · deba999/leetcode Expand file tree/ Copy path257.pyMore file actions 63 lines (53 loc) · 1.49 KB / Copy path257.pyFile metadata and controls63 lines (53 loc) · 1.49 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 55 56 57 58 59 60 61 62 63 #!/usr/bin/python # -*- coding: utf-8 -*- # Author: Yu Zhou # 257. Binary Tree Paths # 思路: # DFS + Stack class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ stack = [(root, "")] res = [] # Edge Case if not root: return [] # res: ["1->3", "1->2->5"] while stack: node, strr = stack.pop() if not node.left and not node.right: res.append(strr + str(node.val)) if node.left: stack.append((node.left, strr + str(node.val) + "->")) if node.right: stack.append((node.right, strr + str(node.val) + "->")) return res # Recursive DFS # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ self.res = [] #Edge if not root: return [] self.dfs(root, "") return self.res def dfs(self, root, strr): if not root.left and not root.right: self.res.append(strr + str(root.val)) if root.left: self.dfs(root.left, strr + str(root.val) + "->") if root.right: self.dfs(root.right, strr + str(root.val) + "->") |
| 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. |