144. Binary Tree Preorder Traversal

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

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,2,3].


题意是要先序遍历一个二叉树。那么一般有两种遍历方式,一种是递归,一种是非递归,因为比较简单,直接上代码。

递归版本:(LeetCode运行3ms),时间复杂度O(n),空间复杂度O(n)

/**
 * Definition for a binary tree node.
 * 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) {
        vector<int> s;
        preorderTraversal(root, s);
        return s;
    }
    void preorderTraversal(TreeNode *root, vector<int> &s) {
        if (root != NULL) {
            s.push_back(root -> val);
            preorderTraversal(root -> left, s);
            preorderTraversal(root -> right, s);
        }
    }
};


非递归版本:(LeetCode运行3ms),时间复杂度O(n), 空间复杂度O(n)

/**
 * Definition for a binary tree node.
 * 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;
        vector<int> visit;
        TreeNode *pointer = root;
        s.push(NULL);
        while (pointer) {
            visit.push_back(pointer -> val);
            if (pointer -> right != NULL) {
                s.push(pointer -> right);
            }
            if (pointer -> left != NULL) {
                pointer = pointer -> left;
            } else {
                pointer = s.top();
                s.pop();
            }
        }
        return visit;
    }
};




阅读更多
个人分类: 二叉树
上一篇150. Evaluate Reverse Polish Notation
下一篇94. Binary Tree Inorder Traversal
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭