[Leetcode][Tree][Binary Tree Preorder Traversal]

二叉树的前序遍历:root点先被访问,然后是left和right子节点。迭代的版本也相对好写。

 

1、递归版本:时间复杂度O(N),空间复杂度O(N)

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void dfsPreorderTraversal(TreeNode *root, vector<int> &res) {
13         if (root == NULL) {
14             return;
15         }
16         res.push_back(root->val);
17         dfsPreorderTraversal(root->left, res);
18         dfsPreorderTraversal(root->right, res);
19     }
20     vector<int> preorderTraversal(TreeNode *root) {
21         vector<int> res;
22         dfsPreorderTraversal(root, res);
23         return res;
24     }
25 };

总结:CE一次,vector类型定义错了。

 

2、迭代版本:时间复杂度O(N),空间复杂度O(N)

/**
 * 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> preorderTraversal(TreeNode *root) {
        stack<TreeNode*> s; // s stores the sequence of TreeNodes
        vector<int> res;   // res stores the result
        s.push(root);
        while (!s.empty()) {
            TreeNode *now = s.top(); //如果now定义在循环外面,程序的效率会有怎么样的区别?
            s.pop();
            if (now != NULL) {
                res.push_back(now->val);
                s.push(now->right);
                s.push(now->left);
            }
        }
        return res;
    }
};

总结:CE3次。。。stack的用法老是忘掉。。。其实就是push、pop和top。

 

3、Morris前序遍历?

等以后有必要的时候再深入研究。

 

4、递归和迭代程序的本质区别?

迭代本质上是模拟递归的过程,避免了多次的程序调用,效率更高。

posted @ 2014-06-28 11:48  poemqiong  阅读(141)  评论(0编辑  收藏  举报