Leetcode - 144. Binary Tree Preorder Traversal (层次遍历)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode - 144. Binary Tree Preorder Traversal (层次遍历)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given a binary tree, return the?preorder?traversal of its nodes' values.
Example:
Input:?[1,null,2,3]1\2/3Output:?[1,2,3]Follow up:?Recursive solution is trivial, could you do it iteratively?
def preOrderTraversal(self,root):# 遞歸res = []def dfs(self,root):if not root:returnres.append(root.val)dfs(root.left)dfs(root.right)dfs(root)return res# 非遞歸stack = [root]res = []while stack:node = stack.pop()res.append(node.val)if node.right:stack.append(node.right)if node.left:stack.append(node.left)return res?
總結
以上是生活随笔為你收集整理的Leetcode - 144. Binary Tree Preorder Traversal (层次遍历)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode - 169. Majo
- 下一篇: Leetcode - 230. Kth