# 【LeetCode】 144. Binary Tree Preorder Traversal ## Description > 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] ``` ## Solution * 二元樹中的基本題。使用遞迴跑每個節點,先加入自己,有左邊就往左邊走,然後往右邊走。 * 如果想得到中序或後序,只需要改變下方code中Line`16`~`18`的順序即可。 * [94. Binary Tree Inorder Traversal](https://hackmd.io/s/rJeTH3bT4) * [145. Binary Tree Postorder Traversal](https://hackmd.io/s/BkETP3WaN) ### Code ```C++=1 /** * 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: void GetPreorder(TreeNode* root, vector<int>& v) { if(root) { v.push_back(root->val); GetPreorder(root->left,v); GetPreorder(root->right,v); } } vector<int> preorderTraversal(TreeNode* root) { vector<int> v; GetPreorder(root, v); return v; } }; ``` ###### tags: `LeetCode` `C++`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up