题解 | #二叉树的中序遍历#

二叉树的中序遍历

https://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d

vector<int> InOrder(TreeNode* head){
    vector<int> ans;
    vector<TreeNode*> helpans;
    TreeNode* index = head;
    TreeNode* temp = NULL;
    if(head == NULL)    return ans;
    while(index != NULL){
        helpans.push_back(index);
        index = index->left;
    }
    while(!helpans.empty()){
        temp = helpans.back();
        ans.push_back(temp->val);
        helpans.pop_back();
        index = temp->right;
        while(index != NULL){
            helpans.push_back(index);
            index = index->left;
        }
    }
    return ans;
}

不知道为啥核心代码模式一直编译错误,所以我直接用模板提交了,讲一下算法流程和思路。

根左右->根右左->左右根

预处理:头节点的左边界入栈

---------------------------------------------------------------------------------------------------

1) 处理cur节点(左边界最左那个)

2) 弹出cur节点

3) cur节点左孩子的右边界入栈

---------------------------------------------------------------------------------------------------

栈空时跳出

#23届找工作求助阵地##我的实习求职记录#
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务