二叉树的前序遍历,简单易懂
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[1,2]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public List<Integer> preorderTraversal(TreeNode root) { 18 List<Integer> res = new ArrayList<>(); 19 if(root == null) return res; 20 21 Stack<TreeNode> stack = new Stack<>(); 22 stack.push(root); 23 24 while(!stack.isEmpty()){ 25 TreeNode node = stack.pop(); 26 res.add(node.val); 27 if(node.right != null) stack.push(node.right); 28 if(node.left != null) stack.push(node.left); 29 } 30 return res; 31 } 32 }