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]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.分析:这道题用递归方法很好做,但是此题却提示用循环方法解决。首先我用递归方法,把层次遍历转化为中序遍历,看代码实现就会明白:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void traversal(TreeNode* root,vector<int> &data) { if(root==NULL) return; traversal(root->left,data); data.push_back(root->val); traversal(root->right,data); } vector<int> inorderTraversal(TreeNode *root) { vector<int> data; traversal(root,data); return data; } };
循环实现,这题就有点难度了,不过没关系,我们可以借用栈空间来解决这题。树中某结点不为空,则将其左结点压入栈中,如果没有,则弹出该节点,将该节点的值存入vector中,再压入出栈元素的右结点,依次进行循环遍历,直到栈为空为止。
/** * 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) { stack<TreeNode*> StackTree; vector<int> data; if(root==NULL) return data; TreeNode *CurrentNode=root; while(!StackTree.empty()||CurrentNode) { if(CurrentNode!=NULL) { StackTree.push(CurrentNode); CurrentNode=CurrentNode->left; } else { CurrentNode=StackTree.top(); StackTree.pop(); data.push_back(CurrentNode->val); CurrentNode=CurrentNode->right; } } return data; } };