zoukankan      html  css  js  c++  java
  • [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);
                    }
                }
            }
        }
    };
  • 相关阅读:
    【贪心算法】POJ-3040 局部最优到全局最优
    【贪心算法】POJ-1017
    【贪心算法】POJ-2393 简单贪心水题
    【贪心算法】POJ-3190 区间问题
    项目选题报告(团队)
    结对项目第一次作业——原型设计
    第三次作业团队展示
    软工实践第二次作业——数独
    软件工程实践第一次作业--准备
    字符串
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3416988.html
Copyright © 2011-2022 走看看