相似題目:
二叉樹的前序遍歷:http://blog.csdn.net/Arcome/article/details/53672912
二叉樹的中序遍歷:http://blog.csdn.net/arcome/article/details/53672748
二叉樹的後序遍歷:http://blog.csdn.net/Arcome/article/details/53740883
Problem
Given a binary tree, return the inorder traversal of its nodes' values.
Note:
Recursive solution is trivial, could you do it iteratively?
Example
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Algorithm
整理一下題意:給定一棵二叉樹,要求返回其中序遍歷結果。
首先是熟悉的遞歸版中序遍歷的方法。將訪問節點的操作設置在左節點的遞歸和右節點的遞歸之間。
代碼如下。
//遞歸版本,用時0ms
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
inorder(result,root);
return result;
}
void inorder(vector<int>& result,TreeNode* root){
if(root==NULL) return;
if(root->left!=NULL) inorder(result,root->left);
result.push_back(root->val);
if(root->right!=NULL) inorder(result,root->right);
}
};
對於非遞歸的實現,需要使用棧。
代碼如下。
//非遞歸版本,用時6ms
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL||root->left==NULL&&root->right==NULL) return 0;
TreeNode* p;
int sum=0;
queue<TreeNode*> q;
queue<TreeNode*> level;
q.push(root);
while(!q.empty()){
p=q.front();
q.pop();
if(p->left!=NULL&&p->left->left==NULL&&p->left->right==NULL) sum+=p->left->val;
if(p->left!=NULL) q.push(p->left);
if(p->right!=NULL) q.push(p->right);
}
return sum;
}
};
不斷地將左節點壓入棧中,直到左節點爲NULL。然後對棧操作,若棧非空,則將棧頂的節點加入到結果向量中,然後令指針指向右節點。
因爲某個節點作爲父節點時必然也是作爲其父節點的子節點,所以這一方法可以遍歷所有節點。
此方法十分巧妙,需要熟記。