本文主要是介绍leetcode No94. Binary Tree Inorder Traversal,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Question:
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?
中序遍历,左-根-右
Algorithm:
Accepted Code:
/*** 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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!