Binary Tree Inorder Traversal
Given a binary tree, return theinordertraversal of its nodes' values.
For example:
Given binary tree[1,null,2,3]
,
return[1,3,2]
.
Note:Recursive solution is trivial, could you do it iteratively?
递归:
首先需要一直对左子树迭代并将非空节点入栈
节点指针为空后不再入栈
当前节点为空时进行出栈操作,保存栈顶节点到result
将当前指针移到其右子节点上,若存在右子节点,则在下次循环时又可将其所有左子结点压入栈中。这样就保证了访问顺序为左-根-右
复杂度分析
最坏情况下栈保存所有节点,空间复杂度 O\(n\), 时间复杂度 O\(n\).
Last updated
Was this helpful?