題目
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
代碼
public static IList<IList<int>> Method(TreeNode root)
{
IList<IList<int>> res = new List<IList<int>>();
Stack<TreeNode> stack1 = new Stack<TreeNode>(); // 每行數據從左到右讀入
Stack<TreeNode> stack2 = new Stack<TreeNode>(); // 每行數據從右到做讀入
if (root == null)
{
return res;
}
stack2.Push(root);
while (stack1.Count != 0 || stack2.Count != 0)
{
var sub = new List<int>();
TreeNode cur;
if (stack1.Count != 0)
{
while (stack1.Count != 0)
{
cur = stack1.Pop();
sub.Add(cur.val);
if (cur.right != null)
{
stack2.Push(cur.right);
}
if (cur.left != null)
{
stack2.Push(cur.left);
}
}
res.Add(sub);
}
else
{
while (stack2.Count != 0)
{
cur = stack2.Pop();
sub.Add(cur.val);
if (cur.left != null)
{
stack1.Push(cur.left);
}
if (cur.right != null)
{
stack1.Push(cur.right);
}
}
res.Add(sub);
}
}
return res;
}
注意點
- if (root == null),對結點空判斷
- while (stack1.Count != 0 || stack2.Count != 0),while 循環退出條件
可以換一種思路:按正常 BFS 算法進行遍歷,遇到奇數層(從0層開始),將元素反轉。