[Leetcode] Binary Tree Inorder Traversal

来源:互联网 发布:如何更新mac电脑系统 编辑:程序博客网 时间:2024/05/16 23:02

题目:

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

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,3,2].

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


思路:递归的做法非常简单,重点是如何用循环来做。

        整体思路是利用一个堆栈去模拟递归的过程,问题是,如果完全按照递归的过程去做堆栈,那么对于栈顶的元素A需要将左子树压入堆栈,然后当左边的元素弹出堆栈后,弹出A,然后再将右子树压入堆栈。这样,元素A有两次成为栈顶的机会:第一次压入了左子树;第二次弹出,输出,并且压入右子树——递归的做法由于实际压入堆栈的是一个函数,很好的记录了当前状态;可是堆栈无法记录。

        解决的办法有两个,第一种是修改node的结构,加入一个visited的bool成员;第二种是利用一个hashmap去存已经“访问过”的成员(“访问过”在这里的意思是指已经将左子树压栈)。这两种做法都不是最优。

        另一种做法是,设置一个current指针,指向当前的节点。具体做法是:不断的将左子树压入堆栈,直到current的值变为null. 这个时候已经到达了整个树的最左边。这种做法之所以是有效的是因为栈中的元素一定都是已经压入过左子树的,也就是一定是“访问过”的,因此,每当发现A找不到左子树时,只需要将栈顶元素A弹出,输出,然后继续压入右子树。当右子树完全输出完之后,下一个出栈的就是A的父节点B. 此时,对于B来说,他的左子树已经遍历完了。

        对于循环的终止条件,当栈为空时,并不一定意味着循环结束。这是因为只要当current不为空,就会继续向栈中压入节点。因此当这两条均不满足时,循环才算彻底结束。


class Solution {public:    vector<int> inorderTraversal(TreeNode *root) {        vector<int> result;        if (root == nullptr) return result;        stack<TreeNode*> path;        TreeNode* current = root;        while (!path.empty() || current != nullptr) {            if (current != nullptr) {   //keep pushing the left subtree                path.push(current);                current = current->left;            } else {   //until reach the end                current = path.top();   //current's left subtree has all been visited                path.pop();                result.push_back(current->val);   //output current                current = current->right;   //redirect to its right subtree            }        }        return result;    }};


总结:复杂度为O(n).

0 0