首页 > 代码库 > Binary Tree Preorder Traversal
Binary Tree Preorder Traversal
https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
很简单,递归。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List list = new ArrayList<Integer>(); if(root == null){ return list; } list.add(root.val); list.addAll(preorderTraversal(root.left)); list.addAll(preorderTraversal(root.right)); return list; }}
但原题提出不用递归的方法,即遍历。使用stack,遇到一个节点,首先list.add(root.val),如果左节点不为空,下移到左节点,同时如果右节点不为空,将右节点推入stack。如果左节点为空,从stack中弹出最上面的节点作为下一个节点,循环处理。直到stack为空,而且当前处理节点为空。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); while(!stack.empty() || root != null){ if(root == null){ return list; } list.add(root.val); if(root.right != null){ stack.push(root.right); } if(root.left != null){ root = root.left; }else{ if(!stack.empty()){ root = stack.pop(); }else{ root = null; } } } return list; }}
Binary Tree Preorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。