原题:
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]
.
=>返回[1,3,2]
Note: Recursive solution is trivial, could you do it iteratively?
=>递归的算法很简单,能否不递归实现?
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode *root) { } };
晓东解析:
这个题目和之前的先序遍历以及后序遍历是一样的,就不多做解释了,见相应的博文:http://blog.csdn.net/u011960402/article/details/14517135以及http://blog.csdn.net/u011960402/article/details/15499903。
代码实现:
1)递归实现:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> result; vector<int> left; vector<int> right; if(NULL == root) return result; left = inorderTraversal(root->left); if(left.size() != 0) result.insert(result.end(), left.begin(), left.end()); result.push_back(root->val); right = inorderTraversal(root->right); if(right.size() != 0) result.insert(result.end(), right.begin(), right.end()); return result; } };
执行结果:
67 / 67 test cases passed.
|
Status:
Accepted |
Runtime: 36 ms
|
2)非递归实现
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> result; stack<TreeNode*> TreeStack; if(NULL == root) return result; while(root || !TreeStack.empty()){ while(root){ TreeStack.push(root); root = root->left; } root = TreeStack.top(); result.push_back(root->val); TreeStack.pop(); root = root->right; } } };
执行结果:
67 / 67 test cases passed.
|
Status:
Accepted |
Runtime: 36 ms
|
若您有更好的算法,欢迎提出指正。