LeetCode 144. 二叉树的前序遍历
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
题解:
方法一:递归方式
先序遍历为先根然后左子树、右子树。
/**
* 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 {
private List<Integer> list;
public List<Integer> preorderTraversal(TreeNode root) {
list = new ArrayList<Integer>();
dfs(root);
return list;
}
public void dfs(TreeNode root){
if(root == null)return;
list.add(root.val);
dfs(root.left);
dfs(root.right);
}
}
方法二:非递归实现,显式模拟栈。
/**
* 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> list = new ArrayList<Integer>();
if(root == null)
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
while(!stack.isEmpty() || p != null){
/*一直往左走,处理左子树*/
while(p != null){
list.add(p.val);
stack.push(p);
p = p.left;
}
/*无左子树,再处理右子树*/
p = stack.pop();
p = p.right;
}
return list;
}
}
题目链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
题解参考:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/er-cha-shu-de-qian-xu-bian-li-by-leetcode-solution/