二叉树的中序遍历

  1. Binary Tree Inorder Traversal(easy)
    Given the root of a binary tree, return the inorder traversal of its nodes’ values.
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

中序遍历的实现方式:访问完左子树,再访问根节点,最后访问右子树。

  1. 递归
    递归的程序很简单,此处不提
  2. 迭代1
    使用栈,循环不嵌套。树节点cur指向根节点,cur不为空或者stack不为空,迭代继续。如果cur不为空,cur入栈,继续访问cur的左孩子cur=cur->left。如果cur为空,cur=栈顶元素,将cur->val保存到res数组中,cur=cur->right.
    由中序遍历的定义可知,遍历到一个节点时(输出),其左子树已经被遍历完毕(对应程序,此时cur=null,说明在当前子树上已经遍历完毕),开始遍历其右子树(cur=cur->right)

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>res;
        if(!root){
            return res;
        }
        TreeNode *cur=root;
        stack<TreeNode*>s;
        while(cur||!s.empty()){
            if(cur){
                s.push(cur);
                cur=cur->left;
            }else{
                cur=s.top();
                s.pop();
                res.push_back(cur->val);
                cur=cur->right;
            }
        }
        return res;
    }
};
  1. 迭代
    cur指向当前节点,cur!=null时,将cur入栈,cur下沉到cur的左孩子。cur=null时,弹出栈顶元素,输出,cur下沉到cur的右孩子。
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>res;
        stack<TreeNode*>s;
        TreeNode* cur=root;
        while(cur||!s.empty()){
            while(cur){
                s.push(cur);
                cur=cur->left;
            }
            cur=s.top();
            s.pop();
            res.push_back(cur->val);
            cur=cur->right;
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值