144,145 二叉樹的前序,後序遍歷(中等,困難)
阿新 • • 發佈:2018-12-16
給定一個二叉樹,返回它的 前序 遍歷。
示例:
輸入: [1,null,2,3] 1 \ 2 / 3 輸出: [1,2,3]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ def dummy(root,l): if not root: return result.append(root.val) if root.left: dummy(root.left,result) if root.right: dummy(root.right,result) result=[] dummy(root,result) return result
執行用時: 44 ms, 在Binary Tree Preorder Traversal的Python3提交中擊敗了98.03% 的使用者
給定一個二叉樹,返回它的 後序 遍歷。
示例:
輸入: [1,null,2,3] 1 \ 2 / 3 輸出: [3,2,1]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ def dummy(root,l): if not root: return if root.left: dummy(root.left,result) if root.right: dummy(root.right,result) result.append(root.val) result=[] dummy(root,result) return result
執行用時: 44 ms, 在Binary Tree Postorder Traversal的Python3提交中擊敗了97.88% 的使用者