leetcode 94.Binary Tree Inorder Traversal 二叉树的中序遍历

递归算法C++代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> inorderTraversal(TreeNode* root) {
13         vector<int> tra;
14         Morder(root,tra);
15         return tra;
16     }
17     void Morder(TreeNode* root,vector<int> &tra){
18         if(root==NULL) return;
19         if(root->left)
20             Morder(root->left,tra);
21         tra.push_back(root->val);
22         if(root->right)
23             Morder(root->right,tra);
24     }
25 };

 非递归方法(迭代):

C++代码:

猜你喜欢

转载自www.cnblogs.com/joelwang/p/10332595.html