标签:
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]
.
inorder, 即按照“左根右”的顺序遍历,
1、当前访问节点不为空,则一直向左遍历,当前节点压栈
2、否则,取栈顶节点访问之,并遍历右节点
1 vector<int> inorderTraversal(TreeNode *root) 2 { 3 vector<int> tree_nodes; 4 stack<TreeNode*> stree; 5 TreeNode* visit = root; 6 7 while (!stree.empty() || (visit != NULL)) 8 { 9 if (visit != NULL) // if visit is not empty, push it into stack and visit left 10 { 11 stree.push(visit); 12 visit = visit->left; 13 } 14 else // visit is null, get top node from stack, visit it, and put visit to right 15 { 16 visit = stree.top(); 17 stree.pop(); 18 tree_nodes.push_back(visit->val); 19 visit = visit->right; 20 } 21 } 22 23 return tree_nodes; 24 }
leetcode 94. Binary Tree Inorder Traversal
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4231546.html