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

For example: Given binary tree [1,null,2,3],

   1
\
2
/
3

return [1,3,2].

Note: Recursive(递归) solution is trivial, could you do it iteratively(迭代)?

思路:

解法一:用递归方法很简单,

(1)如果root为空,则返回NULL;

(2)如果root->left != NULL,则返回左子树的中序遍历元素;

(3)如果root->right != NULL, 则返回右子树的中序遍历元素;

(4)最后,将左子树的中序遍历元素放入容器,root->val放入容器,再将右子树的中序遍历元素放入容器;

(5)返回容器;

 /**
* 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 {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> v, v1, v2;
int i;
if(root == NULL)
return v;
if(root->left != NULL)
v1 = inorderTraversal(root->left);
if(root->right != NULL)
v2 = inorderTraversal(root->right);
for(i = ; i < v1.size(); i++)
v.push_back(v1[i]);
v.push_back(root->val);
for(i = ; i < v2.size(); i++)
v.push_back(v2[i]);
return v;
}

解法二:非递归中序遍历二叉树,要定义一个栈(stack)

 class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> v;
stack<TreeNode*> node_stack;
TreeNode* pNode = root;
while((pNode != NULL) || !node_stack.empty()){
//节点不为空,加入栈中,并访问节点左子树
if(pNode != NULL){
node_stack.push(pNode);
pNode = pNode->left;
}
else{
//节点为空,从栈中弹出一个节点,访问这个节点,
pNode = node_stack.top();
node_stack.pop();
v.push_back(pNode->val);
//访问节点右子树
pNode = pNode->right;
}
}
return v;
}
};
05-02 08:15