本文主要是介绍Leetcode 144. Binary Tree Preorder Traversal二叉树前序遍历,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1\2/3Output:[1,2,3]
题目链接:https://leetcode.com/problems/binary-tree-preorder-traversal/
/*** 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:void pre_order(TreeNode* root,vector<int>&res){if(root){res.emplace_back(root->val);pre_order(root->left,res);pre_order(root->right,res);}}vector<int> preorderTraversal(TreeNode* root) {vector<int> res;pre_order(root,res);return res;}
};
---------------------2019.8.12复习
-------------------2021年3月10日14:41:09
-----------------------2021年4月30日19:48:03
非递归方式
class Solution {
public:vector<int> preorderTraversal(TreeNode* root) {vector<int> res;if(!root){return res;}stack<TreeNode*> stk;stk.push(root);while(!stk.empty()){TreeNode *node=stk.top();stk.pop();res.push_back(node->val);if(node->right){stk.push(node->right);}if(node->left){stk.push(node->left);}}return res;}
};
这篇关于Leetcode 144. Binary Tree Preorder Traversal二叉树前序遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!