标签:
Binary Tree Preorder Traversal
问题:
Given a binary tree, return the preorder traversal of its nodes‘ values.
Recursive solution is trivial, could you do it iteratively?
思路:
栈的方法 弹出栈顶的时候 先加入有节点 再加入做节点 直到栈空
我的代码:
public 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>(); stack.push(root); do { TreeNode node = stack.pop(); list.add(node.val); if(node.right != null) stack.push(node.right); if(node.left != null) stack.push(node.left); }while(!stack.isEmpty()); return list; } }
他人代码:
public class Solution { public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> preorder = new ArrayList<Integer>(); if (root == null) { return preorder; } stack.push(root); while (!stack.empty()) { TreeNode node = stack.pop(); preorder.add(node.val); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } return preorder; } }
学习之处:
Binary Tree Preorder Traversal
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4313339.html