给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
思路:递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<int> InorderTraversal(TreeNode root)
{
IList<int> ans=new List<int>();
tree(root,ans);
return ans;
}
public void tree(TreeNode root,IList<int> list)
{
if(root!=null)
{
if(root.left!=null)
tree(root.left,list);
list.Add(root.val);
if(root.right!=null)
tree(root.right,list);
}
}
}
时间复杂度:O(n)空间复杂度:O(n)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/submissions/