Total Accepted: 97599 Total Submissions: 257736 Difficulty: Medium
Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
(M) Binary Tree Inorder Traversal (M) Verify Preorder Sequence in Binary Search Tree
/** * 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) { vector<int> res; TreeNode* p = root; if(p==NULL){ return res; } stack<TreeNode*> stk; while(p || !stk.empty()){ while(p){ res.push_back(p->val); stk.push(p); p=p->left; } if(!stk.empty()){ p = stk.top()->right; stk.pop(); } } return res; } };
Next challenges: (M) Binary Tree Inorder Traversal (M) Verify Preorder Sequence in Binary Search Tree
时间: 2024-12-30 03:29:25