赞
踩
给定一个二叉树,返回它的前序遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
分析:先根节点后左右子节点。
Python版本:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
Java版本:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { List<Integer> list=new ArrayList<>(); public List<Integer> preorderTraversal(TreeNode root) { if(root==null)return list; list.add(root.val); preorderTraversal(root.left); preorderTraversal(root.right); return list; } }
分析:用栈迭代,处理完根节点后,按照先右节点,最后左节点的顺序入栈。总体的处理顺序就是中-左-右。
Python版本:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] stack = [root] res = [] while stack: cur = stack.pop() res.append(cur.val) if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) return res
Java版本:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { List<Integer> list=new ArrayList<>(); public List<Integer> preorderTraversal(TreeNode root) { if(root==null) return list; Stack<TreeNode>stack=new Stack<>(); while(root!=null||!stack.isEmpty()){ while(root!=null){ list.add(root.val); stack.push(root); root=root.left; } if(!stack.isEmpty()){ root=stack.pop(); root=root.right; } } return list; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。