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);
                    }
                }
            }
        }
    };
  • 相关阅读:
    ssh速度慢
    ps -ef和ps aux的区别
    docker国内镜像加速
    pptpd的log整理
    docker入门2--生命周期
    docker入门1--简介、安装
    Cent7.2单用户模式
    shell中得到当下路径所有文件夹名称
    在centos 7下升级内核
    Mysql如何将一张表重复数据删除
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3416988.html
Copyright © 2011-2022 走看看