【每日一题】【集合非空判断】【逻辑运算符】2021年12月15日-144. 二叉树的前序遍历
/** * 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 { List<Integer> res = new ArrayList<>(); public List<Integer> preorderTraversal(TreeNode root) { preOrder(root); return res; } public void preOrder(TreeNode root) { if(root == null) { return; } Stack<TreeNode> stack = new Stack<>(); //表示栈非空需要使用函数 while(!stack.isEmpty() || root != null) { while(root != null) { //栈内元素可能为空,只剩一个root,右子树 res.add(root.val); stack.push(root); root = root.left; } root = stack.pop().right; } } }
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/15692986.html