二叉树的中序遍历
难度:简单
题目描述
给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
示例1
输入: root = [1,null,2,3]
输出:[1,3,2]
示例2
输入: root = []
输出:[]
示例3
输入: root = [1]
输出:[1]
题解
根据中序遍历的基本思想直接写出即可
想法代码
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null)
{
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution
{
public static void Main(String[] args)
{
TreeNode root = new TreeNode(1)
{
right = new TreeNode(2)
{
left = new TreeNode(3)
}
};
Solution solution = new Solution();
IList<int> ans = solution.InorderTraversal(root);
foreach (int x in ans)
{
Console.Write(x + " ");
}
}
public IList<int> InorderTraversal(TreeNode root)
{
IList<int> ans = new List<int>();
BackTrack(root, ans);
return ans;
}
public void BackTrack(TreeNode root, IList<int> ans)
{
if (root == null)
{
return;
}
BackTrack(root.left, ans);
ans.Add(root.val);
BackTrack(root.right, ans);
}
}