/
* Author: Raghavendra Mallela
*/
* LeetCode 144: Binary Tree PreOrder Traversal
* Given the root of a binary tree, return the preorder traversal of its nodes' values.
* Example 1:
* Input: root = [1,null,2,3]
* Output: [1,2,3]
* Example 2:
* Input: root = []
* Output: []
* Example 3:
* Input: root = [1]
* Output: [1]
* Example 4:
* Input: root = [1,2]
* Output: [1,2]
* Example 5:
* Input: root = [1,null,2]
* Output: [1,2]
* Constraints:
* The number of nodes in the tree is in the range [0, 100].
* -100 <= Node.val <= 100
* Follow up: Recursive solution is trivial, could you do it iteratively?
*/
* PreOrder Traversal is Left, Root, Right
* Recursive Approach where we traverse through the left subtree and
* once child is reached, print the current node and traverse to right
* Iterative approach is to use a stack.
*/
// Recursive approach
void preorder_r(TreeNode* root, vector<int>& res) {
// Check if the root is NULL
if (root == NULL) {
return;
}
// Push the root value to result
res.push_back(root->val);
// Traverse the left subtree
preorder_r(root->left, res);
// Traverse the right subtree
preorder_r(root->right, res);
return;
// Iterative approach
void preorder_i(TreeNode* root, vector<int>& res) {
// Check if the root is NULL
if (root == NULL) {
return;
}
// stack to store the nodes
stack<TreeNode*> st;
// Push the root node to stack
st.push(root);
// Loop while the stack is not empty
while (!st.empty()) {
// Retreive the top node from stack
TreeNode* node = st.top();
st.pop();
// Push the current node value to result
res.push_back(node->val);
// Push the right node first to stack
if (node->right) {
st.push(node->right);
}
// Push the left node to stack
if (node->left) {
st.push(node->left);
}
}
return;
vector<int> preorderTraversal(TreeNode* root) {
// vector to store the result
vector<int> res;
//preorder_r(root, res);
preorder_i(root, res);
return res;
-
独瘾 发布于 2025-09-01 13:05:09
在数字时代,信息的获取与分享变得前所未有的便捷。/这个简单的符号却时常被忽视其背后的深意——它不仅是分隔的标志、断句的开始或结束;更是思考间隙中的停顿符号。/提醒我们:在网络洪流中保持清醒和批判性思维至关重要。”
-
浮华黯淡失色的美 发布于 2025-09-01 19:52:26
在知识的海洋里,每一个标点符号/都像是智慧的灯塔,它们不仅照亮了文字的航道/,更引领着心灵的小舟穿越思想的迷雾。
-
开到荼蘼 发布于 2025-09-01 22:06:58
在这个信息爆炸的时代,/ 却成了太多人思考的终点,他们满足于表面的碎片化知识而不愿深入探究;在无休止地滑动屏幕中迷失了自我价值与方向感// 我们是否正逐渐丧失深度阅读和独立思考的能力?当每个观点都以问句结束而非坚实论证时,/ 不再是引向真理的道路标记而变成了思维懒惰者的避风港。
-
秋若水 发布于 2025-09-02 07:18:23
在这个信息爆炸的时代,/ 成为了我们思考的断层线,人们习惯于快速消费碎片化内容而不愿深入探究本质;在无休止地滑动屏幕中寻找慰藉时却忽略了真正的自我反思与成长空间被无情压缩的事实。
-
花月夜 发布于 2025-09-02 13:02:09
生活就像一场马拉松,/ 🏃♂️ 不在于瞬间的爆发力而取决于持久的耐力,加油!坚持就是胜利的秘诀!
-
迷你仙 发布于 2025-09-02 23:05:50
那片森林,在晨曦的轻抚下缓缓苏醒/树叶间低语着昨夜星辰的故事。
-
如梦歌 发布于 2025-09-05 23:42:30
在纷繁复杂的数字时代,/ 不仅是一个简单的分隔符或除号,它象征着思考的转折点、生活的分界线——是过去与未来的交汇处;也是个人成长中不可或缺的一环:我们用它来总结经验教训并开启新的篇章。 / 提醒着我们不断前行的同时也要时常回望和反思,断舍离旧我以迎接新开始,正如人生旅途中的每一个里程碑般重要而深刻的意义所在!