首页 > 其他 > 详细

LeetCode Binary Tree Preorder Traversal

时间:2015-03-06 17:03:47      阅读:148      评论:0      收藏:0      [点我收藏+]

1.题目

Given a binary tree, return the preorder traversal of its nodes‘ values.

For example:
Given binary tree {1,#,2,3},

   1
         2
    /
   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?


2.解决方案1


class Solution { 
public: 
    vector<int> preorderTraversal(TreeNode *root) { 
        vector<int> ans; 
        deque<TreeNode*> node_list; 
        if(root == NULL) return ans; 
        node_list.push_front(root); 
        while(!node_list.empty()) 
        { 
            TreeNode *cur = node_list.back(); 
            node_list.pop_back(); 
            ans.push_back(cur -> val); 
            if(cur -> right != NULL) node_list.push_back(cur -> right); 
            if(cur -> left != NULL) node_list.push_back(cur -> left); 
        } 
         
        return ans; 
    } 
};
思路:先序遍历的非递归方式还比较容易写,就是广度优先或者呼吸遍历。要一个队列来支撑。


3.解决方案2


class Solution {
public:
    vector<int> path;
    void preorder(TreeNode *root){
        if(!root)
           return;
        path.push_back(root->val);
        //if(root->left)
          preorder(root->left);
        //if(root->right)
          preorder(root->right);
    }
    vector<int> preorderTraversal(TreeNode *root) {
        preorder(root);
        return path;
    }
};

思路:递归就是简单,但是速度很慢。

http://www.waitingfy.com/archives/1594


LeetCode Binary Tree Preorder Traversal

原文:http://blog.csdn.net/fox64194167/article/details/44100695

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!