本文已收录到:LeetCode刷题 专题
- 42. 接雨水 (Trapping Rain Water)
- [LeetCode] 2. 两数相加 2. Add Two Numbers
- [LeetCode] 19. 删除链表的倒数第N个节点 19. Remove Nth Node From End of List
- [LeetCode] 21. 合并两个有序链表(Merge Two Sorted Lists)
- [LeetCode] 24. 两两交换链表中的节点(Swap Nodes in Pairs)
- [LeetCode] 61. 旋转链表(Rotate List)
- [LeetCode] 82. 删除排序链表中的重复元素 II(Remove Duplicates from Sorted List II)
- [LeetCode] 83. 删除排序链表中的重复元素(Remove Duplicates from Sorted List)
- [LeetCode] 86. 分隔链表(Partition List)
- [LeetCode] 206. 反转链表(Reverse Linked List)
- [LeetCode] 92. 反转链表 II(Reverse Linked List II)
- [LeetCode] 147. 对链表进行插入排序(Insertion Sort List)
- [LeetCode] 203. 移除链表元素(Remove Linked List Elements)
- [LeetCode] 160. 相交链表(Intersection of Two Linked Lists)
- [LeetCode] 237. 删除链表中的节点 (Delete Node in a Linked List)
- [LeetCode] 328. 奇偶链表 (Odd Even Linked List)
- [LeetCode] 876. 链表的中间结点 (Middle of the Linked List)
- [LeetCode] 1290. 二进制链表转整数 (Convert Binary Number in a Linked List to Integer)
- [LeetCode] 141. 环形链表 (Linked List Cycle)
- [LeetCode] 142. 环形链表 II (Linked List Cycle II)
- [LeetCode] 283. 移动零 (Move Zeroes)
- [LeetCode] 496. 下一个更大元素 I (Next Greater Element I)
- [LeetCode] 503. 下一个更大元素 II (Next Greater Element II)
- [LeetCode] 456. 132模式 (132 Pattern)
- [LeetCode] 20. 有效的括号 (Valid Parentheses)
- [LeetCode] 94. 二叉树的中序遍历 (Binary Tree Inorder Traversal)
- [LeetCode] 144. 二叉树的前序遍历 (Binary Tree Preorder Traversal)
- [LeetCode] 145. 二叉树的后序遍历 (Binary Tree Postorder Traversal)
题目
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
视频讲解
[bilibili cid=”” page=”1″]711060474[/bilibili]
简明思路
递归
代码
/** * 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> result; if (root == NULL) return result; // 根左右遍历 preTraverse(root, result); return result; } void preTraverse(TreeNode* root, vector<int>& result) { result.push_back(root->val); if (root->left) { preTraverse(root->left, result); } if (root->right) { preTraverse(root->right, result); } } };
thanks abc thanks thanks article
You’re welcome, it’s good to help you.