[Leetcode] Binary Tree Inorder Traversal

Binary Tree Inorder Traversal 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/binary-tree-inorder-traversal/description/


Description

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

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?

Solution


class Solution {
private:
    void inOrder(TreeNode* node, vector<int>& res) {
        if (node != NULL) {
            inOrder(node -> left, res);
            res.push_back(node -> val);
            inOrder(node -> right, res);
        }
    }
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        inOrder(root, res);
        return res;
    }
};

解题描述

这道题是经典的二叉树中序遍历问题。上面给出来的是递归的做法。迭代的做法基本想法还是使用栈来模拟递归调用:


class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if (root == NULL)
            return res;
        stack<TreeNode*> nodeStack;

        TreeNode *curNode = root;

        while (curNode != NULL || !nodeStack.empty()) {  // 只有当前节点为空且栈为空的时候遍历才结束
            while (curNode != NULL) {  // 一直探测到左侧分支的尽头
                nodeStack.push(curNode);
                curNode = curNode -> left;
            }
            curNode = nodeStack.top();
            nodeStack.pop();
            res.push_back(curNode -> val);  // 访问当前节点,即父节点(左侧已经为空)
            curNode = curNode -> right;  // 当前节点设置为右子节点
        }


        return res;
    }
};

转载于:https://www.cnblogs.com/yanhewu/p/8330890.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值