标签:
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?
中序遍历,左-根-右
/** * 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> res; vector<int> inorderTraversal(TreeNode* root) { if(root!=NULL) { inorderTraversal(root->left); res.push_back(root->val); inorderTraversal(root->right); } return res; } };
/** * 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> res; stack<TreeNode*> stack; TreeNode* pNode=root; while(pNode||!stack.empty()) { if(pNode!=NULL) //节点不为空,加入栈中,并访问节点左子树 { stack.push(pNode); pNode=pNode->left; } else { pNode=stack.top(); //节点为空,从栈中弹出一个节点,访问这个节点 stack.pop(); res.push_back(pNode->val); pNode=pNode->right; //访问节点右子树 } } return res; } };
leetcode No94. Binary Tree Inorder Traversal
标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52201639