【LeetCode-树】二叉树的前序遍历

题目描述

给定一个二叉树,返回它的 前序 遍历。
示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [1,2,3]

题目链接: https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

思路1

使用递归。代码如下:

/**
 * 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) {
        if(root==nullptr) return {};

        vector<int> ans;
        preOrder(root, ans);
        return ans;
    }

    void preOrder(TreeNode* root, vector<int>& ans){
        if(root==nullptr) return;

        ans.push_back(root->val);
        preOrder(root->left, ans);
        preOrder(root->right, ans);
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(h)

思路2

使用迭代,类似于中序遍历的颜色标记法。代码如下:

/**
 * 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) {
        if(root==nullptr) return {};

        vector<int> ans;
        stack<TreeNode*> nodeStack;
        stack<int> visit;
        nodeStack.push(root); visit.push(0);
        while(!nodeStack.empty()){
            TreeNode* curNode = nodeStack.top(); nodeStack.pop();
            int hasVisit = visit.top(); visit.pop();
            if(hasVisit==0){
                if(curNode->right){
                    nodeStack.push(curNode->right); visit.push(0);
                }
                if(curNode->left){
                    nodeStack.push(curNode->left); visit.push(0);
                }
                nodeStack.push(curNode); visit.push(1);
            }else{
                ans.push_back(curNode->val);
            }
        }
        return ans;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

猜你喜欢

转载自www.cnblogs.com/flix/p/12762608.html
今日推荐