[牛客网-Leetcode] #树 简单 binary-tree-preorder-traversal

二叉树的先序遍历 binary-tree-preorder-traversal

题目描述

求给定的二叉树的前序遍历。
例如:
给定的二叉树为{1,#,2,3},
1↵ ↵ 2↵ /↵ 3↵
返回:[1,2,3].
备注;用递归来解这道题太没有新意了,可以给出迭代的解法么?

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?

解题思路

思路1:递归

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
    
    
public:
    vector<int> preorderTraversal(TreeNode* root) {
    
    
        vector<int> res;
        if(root == NULL) return res;
        preorder(root, res);
        return res;
    }
    void preorder(TreeNode* root, vector<int>& res) {
    
    
        if(root == NULL) return ;
        res.push_back(root -> val);
        preorder(root -> left, res);
        preorder(root -> right, res);
    }
};

思路2:迭代

  • 整体写法和层次遍历很相似,区别是:
    • 前序遍历用的是栈,层次遍历用的是队列
    • 前序遍历由于输出是中左右,根据栈先进后出的特性,入栈时是先右后左,而层次遍历是先左后右依次入队
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
    
    
public:
    vector<int> preorderTraversal(TreeNode* root) {
    
    
        vector<int> res;
        if(root == NULL) return res;
        stack<TreeNode*> mystack;
        mystack.push(root);
        
        while(!mystack.empty()) {
    
    
            TreeNode* temp = mystack.top();
            mystack.pop();
            res.push_back(temp -> val);
            //先右后左
            if(temp -> right) mystack.push(temp -> right);
            if(temp -> left) mystack.push(temp -> left);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/106881763