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; } };