144.二叉树的前序遍历
程序员文章站
2022-03-26 18:23:35
...
题目:
知识提要:
前序遍历的规则是
若节点为空,则空操作返回;
否则先访问根节点,
然后前序遍历左子树
再前序遍历右子数
代码一:递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
preorder(root,ans);
return ans;
}
public void preorder(TreeNode node,List list){
if(node == null)
return;
list.add(node.val);
preorder(node.left,list);
preorder(node.right,list);
}
}
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(n) ???????
因为递归的时候隐式地维护了一个栈
代码二:迭代
思路与递归一致,把栈显示实现
//迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while(!stack.isEmpty() || node != null){
while(node != null){//每次把左子树走完
ans.add(node.val);
stack.push(node);
node = node.left;
}
node = stack.pop();
node = node.right;//回到右子树
}
return ans;
}
}
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(n)
上一篇: Gradle之发布(8)