• [LeetCode] Binary Tree Inorder Traversal


    iven 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?

    解题思路:

    结点的访问顺序是,左子树 -> 自己 -> 右子树。对于一个结点,它可以输出的条件是,其子树已经加入list,同时左子树已经访问完成。这里的实现和后序遍历不同,后序遍历只需要记录最近的访问结点即可。但中序遍历得记录更多。故为每一个结点引入一个状态位。初始加入为0,当它的左右子树都加入时,修改为1(可以输出)。

    /**
     * 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) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<int> ans;
            list<TreeNode*> node_list;
            list<int> node_state;//0 for not push left and right
            if(root == NULL)
                return ans;
            
            node_list.push_front(root);
            node_state.push_front(0);
            TreeNode *cur = NULL;
            int state = 0;
            
            while(!node_list.empty())
            {
                cur = node_list.front();
                node_list.pop_front();
                state = node_state.front();
                node_state.pop_front();
                
                if(state == 1)
                    ans.push_back(cur -> val);
                else
                {
                    if(cur -> right != NULL) 
                    {
                        node_list.push_front(cur -> right);
                        node_state.push_front(0);
                    }
                    node_list.push_front(cur);
                    node_state.push_front(1);
                    if(cur -> left != NULL) 
                    {
                        node_list.push_front(cur -> left);
                        node_state.push_front(0);
                    }
                }
            }
        }
    };
  • 相关阅读:
    为调试JavaScript添加输出窗口
    后悔自己没有学好数学
    IEnumeralbe<T>被误用一例
    开发软件真是一件有意思的事情
    在网页上实现WinForm控件:ComboBox
    WinForm异步编程中一个容易忽视的问题
    网页上的DataGridView
    用Excel生成代码
    游戏处女作 打方块
    用GDI+保存Image到流时的一个有趣现象
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3416988.html
Copyright © 2020-2023  润新知