标签:iter val value etc put solution des while input
Given a binary tree, return the preorder traversal of its nodes‘ values.
Example:
Input:[1,null,2,3]
1 2 / 3 Output:[1,2,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; } }
leetcode [144]Binary Tree Preorder Traversal
标签:iter val value etc put solution des while input
原文地址:https://www.cnblogs.com/xiaobaituyun/p/10738809.html