题目
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
示例 4:
输入:root = [1,2] 输出:[2,1]
示例 5:
输入:root = [1,null,2] 输出:[1,2]
解题:
方法一:递归
python解法
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: def inorder(root): if not root: return inorder(root.left) res.append(root.val) inorder(root.right) res = [] inorder(root) return res
可以找到规律,将先序遍历改成中序遍历只需要将res.append(root.val)
放到中间即可
c++解法
class Solution { public: void inorder(TreeNode*root,vector<int>& res){ if(!root) return; inorder(root->left,res); res.push_back(root->val); inorder(root->right,res); } vector<int> inorderTraversal(TreeNode* root) { vector<int> res; inorder(root,res); return res; } };
方法二:迭代
python解法
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] cur,stack,res = root,[],[] while stack or cur: while cur: stack.append(cur) cur = cur.left cur = stack.pop() res.append(cur.val) cur = cur.right return res
c++解法
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { if(!root) return {}; vector<int> res; stack<TreeNode*> stack; TreeNode* cur=root; while(!stack.empty()||cur){ while(cur){ stack.push(cur); cur=cur->left; } cur=stack.top(); stack.pop(); res.push_back(cur->val); cur=cur->right; } return res; } };