zoukankan      html  css  js  c++  java
  • LintCode 二叉树的中序遍历

    给出一棵二叉树,返回其中序遍历

    样例

    给出二叉树 {1,#,2,3},

       1
        
         2
        /
       3

    返回 [1,3,2].

    挑战 

    你能使用非递归算法来实现么?

    分析:同前序遍历。

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: Inorder in vector which contains node values.
         */
    public:
        vector<int> inorderTraversal(TreeNode *root) {
            // write your code here
          TreeNode *curr=root;
          stack<TreeNode *> mystack;
          vector<int> res;
          while(!mystack.empty()||curr!=NULL)
          {
              while(curr!=NULL)
              {
                  
                  mystack.push(curr);
                  curr=curr->left;
              }
              if(!mystack.empty())
              {
                  curr=mystack.top();
                  res.push_back(curr->val);
                  mystack.pop();
                  curr=curr->right;
              }
          }
          return res;
        }
    };


    用数组指针
    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: Inorder in vector which contains node values.
         */
    public:
        vector<int> inorderTraversal(TreeNode *root) {
            // write your code here
             TreeNode *curr=root;
             TreeNode *mystack[1000];
             int top=0;
             vector<int> res;
             while(top!=0||curr!=NULL)
             {
                 while(curr!=NULL)
                { 
                 
                 mystack[top++]=curr;
                 curr=curr->left;
                }
             
             if(top>0)
             {
                 top--;
                 curr=mystack[top]; 
                 res.push_back(curr->val);
                 curr=curr->right;
                 
             }
             }
             return res;
        }
    };
    

      

  • 相关阅读:
    android activity 生命周期
    Android event logcat的研究
    关于new enhancement的一些知识
    LEAVE LIST-PROCESSING和LEAVE TO LIST-PROCESSING事件的作用
    报错消息写在AT SELECTION-SCREEN OUTPUT和START-OF-SELECTION事件下的区别
    字符串的 Base64 加密和解密
    接口的学习
    IDOC
    ABAP文件上传下载 用SMW0
    获取本机信息如IP 电脑名称等类
  • 原文地址:https://www.cnblogs.com/lelelelele/p/6115300.html
Copyright © 2011-2022 走看看