Leetcode 144.二叉樹的前序遍歷
阿新 • • 發佈:2018-12-10
1.題目描述
給定一個二叉樹,返回它的 前序 遍歷。
示例:
輸入: [1,null,2,3] 1 \ 2 / 3 輸出: [1,2,3]
進階: 遞迴演算法很簡單,你可以通過迭代演算法完成嗎?
2.解法一:遞迴
/** * 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) { //先判空(最簡潔的寫法) if(root){ res.push_back(root->val); preorderTraversal(root->left); preorderTraversal(root->right); } returnres; } private: vector<int> res; };
3.解法二:非遞迴(棧)
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; //使用stack stack<TreeNode*> stack; TreeNode* p = root; //綜合整理出來的迴圈條件while (p || !stack.empty()) { //if(p)的判斷為關鍵點 if (p){ stack.push(p); res.push_back(p->val); p = p->left; } else{ p = stack.top(); stack.pop(); p = p->right; } } return res; } };