• LintCode 二叉树的前序遍历


    给出一棵二叉树,返回其节点值的前序遍历。

    样例

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

       1
        
         2
        /
       3

     返回 [1,2,3].

    挑战 

    你能使用非递归实现么?

    分析:使用非递归实现(栈)

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

      

  • 相关阅读:
    bootmgr is missing
    【转】ahci和IDE的区别
    win10系统故障代码:0xc000014c
    c++小数点后舍入
    关于类里再声明自身类实例的思考
    Java集合
    Python图片转字符画
    102. Binary Tree Level Order Traversal
    1041. Robot Bounded In Circle
    144. Binary Tree Preorder Traversal
  • 原文地址:https://www.cnblogs.com/lelelelele/p/6115274.html
Copyright © 2020-2023  润新知