public
ArrayList<Integer> preorderTraversal(TreeNode root){
//非递归简洁版
if
(root ==
null
)
return
new
ArrayList<>();
}
TreeNode current = root;
ArrayList<Integer> list =
new
ArrayList<>();
Stack<TreeNode> stack =
new
Stack<>();
while
(current !=
null
|| !stack.isEmpty()){
if
(current !=
null
){
list.add(current.val);
stack.push(current);
current = current.left;
}
else
{
current = stack.pop();
current = current.right;
}
}
return
list;
}
后续遍历树的简化版,思路非常简单
|
LeetCode钻研8 前序遍历树
最新推荐文章于 2024-03-27 22:57:21 发布