leetcode刷题日记——Binary Tree Inorder Traversal

来源:互联网 发布:mysql本地数据库地址 编辑:程序博客网 时间:2024/05/22 07:02
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].

问题分析:题目要求就是返回二叉树的中序遍历序列。依照中序列遍历,先左子树,然后节点,然后右子树,最简单的办法就是采用递归的方式。唯一需要注意的就是用来保存遍历序列的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 {    vector<int> inorder;public:    vector<int> inorderTraversal(TreeNode* root) {        if(root==NULL) return inorder;        inorderTraversal(root->left);        inorder.push_back(root->val);        inorderTraversal(root->right);        return inorder;    }};


0 0
原创粉丝点击