给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
public IList<int> InorderTraversal(TreeNode root) {
List<int> listInt = new List<int>();
if (root==null)
{
return listInt;
}
if (root.left!=null)
{
listInt.AddRange(InorderTraversal(root.left));
}
listInt.Add(root.val);
if (root.right!=null)
{
listInt.AddRange(InorderTraversal(root.right));
}
return listInt;
2020 03 31 重新开始刷leetcode 树的知识
栈的方式:
public List<int> inorderTraversal(TreeNode root)
{
List<int> res = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curr = root;
while (curr != null || stack.Count!=0)
{
while (curr != null)
{
stack.Push(curr);
curr = curr.left;
}
curr = stack.Pop();
res.Add(curr.val);
curr = curr.right;
}
return res;
}
}