Binary Tree Inorder Traversal

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?

/**
 * Definition for binary tree
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> vt;
        if (!root){
            return vt;
        }

        std::stack<TreeNode *> stk;
        TreeNode * p = root;

        while(!stk.empty() || p){
            while(p){
                stk.push(p);
                p = p->left;
            }
            if (!stk.empty()){
                TreeNode * q = stk.top();
                stk.pop();

                vt.push_back(q->val);
                if (q->right){
                    p = q->right;
                }else{
                    p = NULL;
                }   
            }
        }

        return vt;
    }
};

原文链接: https://www.cnblogs.com/kwill/archive/2013/06/06/3122809.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/91405

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午1:09
下一篇 2023年2月10日 上午1:11

相关推荐