[leetcode] 144. Binary Tree Preorder Traversal

网友投稿 613 2022-08-23

[leetcode] 144. Binary Tree Preorder Traversal

Description

Given a binary tree, return the preorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3] 1 \ 2 / 3Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

分析

题目的意思是:用非递归的方式实现二叉树的先序遍历

用到了栈,每遍历一个结点,就把值放进vector中,遍历左右孩子的时候,应该先右孩子,然后左孩子,这样栈取出的时候,才是先左后右,这样就是先序遍历。

代码

/** * 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 preorderTraversal(TreeNode* root) { stack s; vector res; if(!root){ return res; } s.push(root); TreeNode* p; while(!s.empty()){ p=s.top(); res.push_back(p->val); s.pop(); if(p->right){ s.push(p->right); } if(p->left){ s.push(p->left); } } return res; }};

参考文献

​​[编程题]binary-tree-preorder-traversal​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java正则表达式API详解(java常用正则表达式)
下一篇:DETRAC-Train-Images转换成VOC格式的数据集
相关文章

 发表评论

暂时没有评论,来抢沙发吧~