1. 程式人生 > >二叉樹遍歷(中序)(遞迴+非遞迴)

二叉樹遍歷(中序)(遞迴+非遞迴)

Binary Tree Inorder Traversal(二叉樹中序遍歷)

Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree{1,#,2,3},

return[1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.


OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.
Here’s an example:

The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

遞迴思想

思路

中序遍歷的遞迴思想實現。

程式碼

vector<int> inorderTraversal(TreeNode *root)
{
    // 二叉樹中序遍歷
    vector<int > v;
    if(root == NULL)return v;
    inorder_help(root, v);
    return v;
}
void inorder_help(TreeNode *root, vector<int > &v)
{
    if(!root)return;
    inorder_help(root->left, v);
    v.push_back(root->val);
    inorder_help(root->right, v);
}

非遞迴思想

思路

用非遞迴模擬二叉樹的中序遍歷,思路是:優先遍歷根節點的左孩子結點,放入一個棧中,遍歷到底;然後從棧中取結點,棧的特點是後進先出,從最後的節點開始加入vector陣列;接著遍歷該結點的右孩子結點,把該孩子結點當作根節點遍歷左孩子結點。
實現的思想和遞迴是一樣的,就是根據中序遍歷的特點,即:

inorder(root -> left);
get(root -> val);
inorder(root -> right);

程式碼

vector<int> inorderTraversal(TreeNode *root)
{
    vector<int > v;
    stack<TreeNode* > s;
    TreeNode *node = root;
    while(!s.empty() || node!=NULL)
    {
        while(node != NULL)
        {
            s.push(node);
            node = node->left;
        }
        node = s.top();
        s.pop();
        v.push_back(node->val);
        node = node->right;
    }
    return v;
}

以上。


版權宣告:本文為博主原創文章,轉載請註明出處。
個人部落格地址:https://yangyuanlin.club
歡迎來踩~~~~