94. Binary Tree Inorder Traversal

题目

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

分析

二叉树的中根遍历,最好写成迭代的。

递归法:

/**
 * 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> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL)
            return res;
        inorder(root->left,res);
        res.push_back(root->val);
        inorder(root->right,res);
        return res;
    }
    void inorder(TreeNode* r,vector<int>& v)
    {
        if(r==NULL)
            return;
        inorder(r->left,v);
        v.push_back(r->val);
        inorder(r->right,v);
    }
};
迭代法:

/**
 * 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> inorderTraversal(TreeNode* root) {
        vector<int> res;//中根遍历结果向量
        stack<TreeNode*> inorder;//迭代法需要的栈
        if(root==NULL)
            return res;
        inorder.push(root);//先压入根节点
        TreeNode* r=root->left;//r指向左子树
        while(!inorder.empty())//如果栈非空
        {
            if(r!=NULL)//r不为NULL,则将r入栈,继续沿左子树遍历
            {
                inorder.push(r);
                r=r->left;
            }
            else//当r为NULL时
            {
                r=inorder.top();//弹出栈顶元素
                inorder.pop();
                res.push_back(r->val);//将值压入向量,进行中根遍历
                r=r->right;//指向右子树
                if(r!=NULL)//如果右子树不为NULL
                {
                    inorder.push(r);//将右子树入栈
                    r=r->left;//沿右子树的左子树继续遍历
                }
            }
        }
        return res;
        
    }
    
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值