首页 > 其他 > 详细

LeetCode144二叉树前序遍历

时间:2020-07-13 01:00:38      阅读:83      评论:0      收藏:0      [点我收藏+]

题目链接

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/description/

题解一:递归

// Problem: LeetCode 144
// URL: https://leetcode-cn.com/problems/binary-tree-preorder-traversal/description/
// Tags: Tree Recursion Stack
// Difficulty: Medium

#include <iostream>
#include <vector>
using namespace std;

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):val(x), left(nullptr), right(nullptr){}
};

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

int main()
{
    cout << "helloworld" << endl;
    // system("pause");
    return 0;
}

题解二:非递归

  • 需要用到栈
  • 注意循环条件
  • 注意是先把右子树存入栈中
// Problem: LeetCode 144
// URL: https://leetcode-cn.com/problems/binary-tree-preorder-traversal/description/
// Tags: Tree Recursion Stack
// Difficulty: Medium

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):val(x), left(nullptr), right(nullptr){}
};

class Solution{
public:
    vector<int> preorderTraversal(TreeNode* root){
        vector<int> result;
        stack<TreeNode*> nodes;
        nodes.push(root);

        while(!nodes.empty()){
            root = nodes.top();
            nodes.pop();
            if(root!=nullptr){
                result.push_back(root->val);
                nodes.push(root->right);
                nodes.push(root->left);
            }
        }
        return result;
    }
};

int main()
{
    cout << "helloworld" << endl;
    // system("pause");
    return 0;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


LeetCode144二叉树前序遍历

原文:https://www.cnblogs.com/chouxianyu/p/13290758.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!