LeetCode94——Binary Tree Inorder Traversal

- 日理万妓 2022-08-21 00:04 231阅读 0赞

LeetCode94——Binary Tree Inorder Traversal

出去调了一天代码,回来就调了两道简单的题目写了。。。
先来一道二叉树的中序遍历,直接递归解决就ok。

原题

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

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].

代码

LeetCode里面数据结构的题链表的题目已经做了不少,现在开始轮到二叉树了,要慢慢拾起来了。

  1. class Solution {
  2. private:
  3. void helper(TreeNode*root, vector<int>&result)
  4. {
  5. if (root == NULL)
  6. return;
  7. helper(root->left,result);//递归左子树
  8. result.push_back(root->val);//访问根
  9. helper(root->right,result);//递归右子树
  10. }
  11. public:
  12. vector<int> inorderTraversal(TreeNode* root) {
  13. vector<int>result;
  14. helper(root, result);
  15. return result;
  16. }
  17. };

发表评论

表情:
评论列表 (有 0 条评论,231人围观)

还没有评论,来说两句吧...

相关阅读