leetcode [144]Binary Tree Preorder Traversal
发布时间:2020-12-14 04:33:10 所属栏目:大数据 来源:网络整理
导读:Given a binary tree,return the? preorder ?traversal of its nodes‘ values. Example: Input:? 1 2 / 3Output:?[1,null,2,3][1,3] Follow up:?Recursive solution is trivial,could you do it iteratively? 题目大意: 使用非递归的解法,得到二叉树的前
Given a binary tree,return the?preorder?traversal of its nodes‘ values. Example: Input:? 1 2 / 3 Output:? [1,null,2,3][1,3] Follow up:?Recursive solution is trivial,could you do it iteratively? 题目大意: 使用非递归的解法,得到二叉树的前序遍历。 解法: 使用栈来做 java: class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer>res=new ArrayList<Integer>(); Stack<TreeNode>rights=new Stack<>(); while(root!=null){ res.add(root.val); if(root.right!=null) rights.add(root.right); root=root.left; if(root==null&&!rights.empty()) root=rights.pop(); } return res; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |