首页 > 代码库 > 145. Binary Tree Postorder Traversal QuestionEditorial Solution
145. Binary Tree Postorder Traversal QuestionEditorial Solution
Given a binary tree, return the postorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
每次都先push right, 然后left。 但是需要一个sentinel存每次上一次pop的node, 如果这个node是新的peek的值的子数的话,不能再push到stack,需要进入输出逻辑。 同样进入输出逻辑的还有leaf。
public IList<int> PostorderTraversal(TreeNode root) { var res = new List<int>(); var stack = new Stack<TreeNode>(); if(root == null) return res; stack.Push(root); var rightPointer = new TreeNode(-1); while(stack.Count() > 0) { if((root.right == null && root.left == null)||(root.left == rightPointer ) || (root.right == rightPointer) ) { res.Add(root.val); rightPointer = stack.Pop(); if(stack.Count()>0) root = stack.Peek(); } else { if(root.right != null) stack.Push(root.right); if(root.left != null) stack.Push(root.left); root = stack.Peek(); } } return res; }
145. Binary Tree Postorder Traversal QuestionEditorial Solution
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。