binary-tree-preorder-traversal(二叉树前序遍历)

版权声明:版权归作者所有,转发请标明 https://blog.csdn.net/weixin_40087851/article/details/81947436

题目描述

  • Given a binary tree, return the preorder traversal of its nodes’ values.
  • For example:Given binary tree{1,#,2,3},return[1,2,3].
  • Recursive solution is trivial, could you do it iteratively?
  • 翻译:给定二叉树,返回二叉树前序遍历(非递归版本)

解析

  • 二叉树的前序遍历是:中->左->右。采用这个次序进行递归求解十分容易。我们直接上代码:
    void recursive(TreeNode *root,vector<int>& res){
        if(root==nullptr)
            return;
        res.push_back(root->val);
        recursive(root->left,res);
        recursive(root->right,res);
    }
  • 递归的思想其实就是栈思想,因此非递归版本采用栈来实现。观察递归版本可知,函数先递归求解左子树,再求解右子树。因而采用栈(先进后出特性)时,为了先处理左子树,再处理右子树,我们只能先将右子树入栈,再将左子树入栈。
    void nonRecursive(TreeNode *root,vector<int>& res){
        stack<TreeNode*> node;
        node.push(root);
        while(node.size()!=0){
            TreeNode *cur=node.top();
            node.pop();
            res.push_back(cur->val);
            if(cur->right!=nullptr)
                node.push(cur->right);
            if(cur->left!=nullptr)
                node.push(cur->left);
        }
    }

总代码

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    void recursive(TreeNode *root,vector<int>& res){
        if(root==nullptr)
            return;
        res.push_back(root->val);
        recursive(root->left,res);
        recursive(root->right,res);
    }

    void nonRecursive(TreeNode *root,vector<int>& res){
        stack<TreeNode*> node;
        node.push(root);
        while(node.size()!=0){
            TreeNode *cur=node.top();
            node.pop();
            res.push_back(cur->val);
            if(cur->right!=nullptr)
                node.push(cur->right);
            if(cur->left!=nullptr)
                node.push(cur->left);
        }
    }

    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> res;
        if(root==nullptr)
            return res;
        //recursive(root,res);
        nonRecursive(root,res);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_40087851/article/details/81947436