Binary Tree Preorder Traversal
程序员文章站
2022-05-31 08:34:37
...
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].
前序遍历一棵树,我们可以用递归,也可以借助堆栈用迭代来解决,因为前序遍历的顺序是根-左-右,因此我们压栈的时候顺序为根-右-左。下面是两个方法的代码:
递归:
迭代:
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
前序遍历一棵树,我们可以用递归,也可以借助堆栈用迭代来解决,因为前序遍历的顺序是根-左-右,因此我们压栈的时候顺序为根-右-左。下面是两个方法的代码:
递归:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); if(root == null) return list; getPreorder(root, list); return list; } public void getPreorder(TreeNode root, List<Integer> list) { if(root == null) return; list.add(root.val); getPreorder(root.left, list); getPreorder(root.right, list); } }
迭代:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if(root == null) return list; stack.add(root); while(!stack.isEmpty()) { TreeNode node = stack.pop(); list.add(node.val); if(node.right != null) { stack.push(node.right); } if(node.left != null) { stack.push(node.left); } } return list; } }
上一篇: nginxconf配置说明
下一篇: 略淡策略模式 策略模式使用
推荐阅读
-
LC 297 Serialize and Deserialize Binary Tree
-
leetcode笔记:Invert Binary Tree
-
Convert Sorted Array to Binary Search Tree
-
minimum-depth-of-binary-tree
-
cf438E. The Child and Binary Tree(生成函数 多项式开根 多项式求逆)
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
21天刷题计划之17.1—maximum-depth-of-binary-tree(二叉树的最大深度)(Java语言描述)
-
21天刷题计划之18.1—balanced-binary-tree(平衡二叉树)(Java语言描述)