【Leetcode_總結】144. 二叉樹的前序遍歷 - python
阿新 • • 發佈:2019-01-11
Q:
給定一個二叉樹,返回它的 前序 遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,2,3]
連結:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/description/
思路:遞迴 前序遍歷二叉樹
程式碼:
# 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] """ if root == None: return [] else: res = [] self.pre_digui(root, res) return res def pre_digui(self,root,res): if root == None: return res.append(root.val) self.pre_digui(root.left,res) self.pre_digui(root.right,res)