Binary Tree Preorder Traversal

Binary Tree Preorder Traversal.png

解題思路 :

Recursive 方式:
pre-order 基本做法三步驟

  1. statements;
  2. recursive call (left)
  3. recursive call (right)

這邊的 statement 就是把數(shù)值存到要回傳的 vector 裡面 當然只處理不是 nullptr 的節(jié)點 所以要設定一個 if statement 來檢查

Non - Recursive 方式:
可以使用 stack 只是放入 stack 的順序是 先 right child 然後才放 left child (倒出來才會是正確順序)

C++ code :

<pre><code>
//Recursive:

void preOrder(TreeNode *root, vector<int> &res)

{

if(root != nullptr){ 
    res.emplace_back(root->val);
    preOrder(root->left, res);
    preOrder(root->right, res);
}

}

class Solution {

public:

/**
 * @param root: The root of binary tree.
 * @return: Preorder in vector which contains node values.
 */
vector<int> preorderTraversal(TreeNode *root) {
    // write your code here
    vector<int> res;
    preOrder(root, res);
    return res;
}

};

<code><pre>

//Non - Recursive

class Solution {

public:

/**
 * @param root: The root of binary tree.
 * @return: Preorder in vector which contains node values.
 */
vector<int> preorderTraversal(TreeNode *root) {
    // write your code here
    vector<int> res;
    if(root == nullptr) return res;
    stack<TreeNode*> s;
    s.push(root);
    while(!s.empty())
    {
        TreeNode *tmp = s.top();
        s.pop();
        res.emplace_back(tmp->val);
        if(tmp->right) s.push(tmp->right);
        if(tmp->left) s.push(tmp->left);
    }
    return res;
}

};

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容