144. Binary Tree Preorder Traversal
Posted dmndxld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 / 3 Output:[1,2,3]
My idea:ricursion
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] res = [] res.append(root.val) if root.left: left = self.preorderTraversal(root.left) res.extend(left) if root.right: right = self.preorderTraversal(root.right) res.extend(right) return res
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] res = [] res.append(root.val) res.extend(self.preorderTraversal(root.left)) res.extend(self.preorderTraversal(root.right)) return res
OTHERS:iretator
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { stack<TreeNode*> s; vector<int> ans; while(true){ while(root){ ans.push_back(root->val); if(root->right) s.push(root->right); root = root->left; } if(s.empty()) break; root = s.top(); s.pop(); } return ans; } };
以上是关于144. Binary Tree Preorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal