题目:
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [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) {
List<int> ret = new List<int>();
if (root == null) return ret;
ret.AddRange(InorderTraversal(root.left));
ret.Add(root.val);
ret.AddRange(InorderTraversal(root.right));
return ret;
}
}
迭代算法
/**
* 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) {
List<int> ret = new List<int>();
Stack<TreeNode> vs = new Stack<TreeNode>();
if (root == null) return ret;
TreeNode tmp = root;
while (tmp != null || vs.Count != 0)
{
while (tmp!=null)
{
vs.Push(tmp);
tmp = tmp.left;
}
if (vs.Count != 0)
{
tmp = vs.Pop();
ret.Add(tmp.val);
tmp = tmp.right;
}
}
return ret;
}
}
来源:
力扣(LeetCode)