二叉树遍历(中序)(递归+非递归)

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
欢迎来踩~~~~


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值