标签:图片 rsa vector img 访问 nbsp roo || bin
递归算法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 };
非递归方法(迭代):通过stack容器
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 //使用栈的非递归方法 14 vector<int> res; 15 stack<TreeNode*> st; 16 TreeNode* T=root; 17 while(T||!st.empty()){ 18 //将T的所有左孩子入栈 19 while(T){ 20 st.push(T); 21 T=T->left; 22 } 23 //访问T的元素,然后转到T的右孩子 24 if(!st.empty()){ 25 T=st.top(); 26 st.pop(); 27 res.push_back(T->val); 28 T=T->right; 29 } 30 } 31 return res; 32 } 33 };
leetcode 94.Binary Tree Inorder Traversal 二叉树的中序遍历
标签:图片 rsa vector img 访问 nbsp roo || bin
原文地址:https://www.cnblogs.com/joelwang/p/10332595.html