码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode 二叉树的前序遍历

时间:2016-11-29 23:02:28      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:turn   nod   cto   value   节点   values   前序遍历   traversal   accordion   

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

样例

给出一棵二叉树 {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;
    }
};

  

LintCode 二叉树的前序遍历

标签:turn   nod   cto   value   节点   values   前序遍历   traversal   accordion   

原文地址:http://www.cnblogs.com/lelelelele/p/6115274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!