参考链接
http://blog.youkuaiyun.com/xshalk/article/details/8152297
题目描述
Binary Tree Inorder Traversal
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]
.
题目分析
中序遍历二叉树:
递归法,不多说,左孩子-》自己-》右孩子这样递归就可以了。
循环法:使用栈,下面的代码还是比较好的。
其中指针p的使用非常关键
总结
三种遍历的递归和非递归法都要熟练代码示例
/*
编译环境CFree 5.0
博客地址:http://blog.youkuaiyun.com/Snowwolf_Yang
*/
#include
#include
#include
using namespace std;
/**
* Definition for binary tree
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void printVector(vector
in,char* name)
{
printf("%s size=%d\n",name,in.size());
for(int i = 0;i< in.size();i++)
{
printf("%d ",in[i]);
}
printf("\n");
}
#if 0
class Solution {
public://中序遍历,左中右
vector
inorderTraversal(TreeNode *root) {
vector
out; if(root == NULL) return out; vector
outleft = inorderTraversal(root->left); vector
outright = inorderTraversal(root->right); out.insert(out.begin(),outright.begin(),outright.end()); out.insert(out.begin(),root->val); out.insert(out.begin(),outleft.begin(),outleft.end()); return out; } }; #elif 1//栈 ------------赞!!!! class Solution { public://中序遍历,左中右 vector
inorderTraversal(TreeNode *root) { vector
out; stack
stk; TreeNode *p = root; while(!stk.empty() || p)//只要是栈不为空或者p不为空就继续 { if(p != NULL)//不停的把左孩子入栈到叶子结点 { stk.push(p); p = p->left; } else //把栈顶元素输出然后把指针指向栈顶元素的右结点。 { p = stk.top(); stk.pop(); out.push_back(p->val); p = p->right; } } return out; } }; #endif /*功能测试*/ void test0() { /* 1 2 3 4 5 6 7 */ TreeNode node1(1); TreeNode node2(2); TreeNode node3(3); TreeNode node4(4); TreeNode node5(5); TreeNode node6(6); TreeNode node7(7); node1.left = &node2; node1.right = &node3; node2.left = &node4; node2.right = &node5; node3.left = &node6; node3.right = &node7; Solution so; vector
out = so.inorderTraversal(&node1); int tmp[7] = {4,2,5,1,6,3,7}; int i = 0; for(i = 0;i<7 && i
推荐学习C++的资料
C++标准函数库
在线C++API查询