root.right =newTreeNode(6); root.right.left =newTreeNode(5); root.right.right =newTreeNode(7); root.right.right.right =newTreeNode(8); System.out.println(Main28.preorderTraversal(root)); } publicstaticclassTreeNode { intval; TreeNode left; TreeNode right; TreeNode(intx) { val = ...
TreeNode(intx) { val = x; } } 第一种方法:算法实现类 importjava.util.LinkedList;importjava.util.List;publicclassSolution{privateList<Integer> result;publicList<Integer>preorderTraversal(TreeNode root){ result =newLinkedList<>(); preOrder(root);returnresult; }privatevoidpreOrder(TreeNode root)...
代码: packagecom.niuke.p7;importjava.util.ArrayList;importjava.util.Stack;publicclassSolution {publicArrayList<Integer>preorderTraversal (TreeNode root) {//write code hereArrayList<Integer> list =newArrayList<>();if(root ==null) {returnlist; } Stack<TreeNode> stack =newStack<>(); stack.push(...
public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length == 0 || inorder.length == 0) return null; return helper(0,inorder.length - 1,preorder,inorder); } private TreeNode helper(int inStart, int inEnd, int[] preorder, int[] inorder){ // Base情况 if...
上边的两种解法,空间复杂度都是O(n),利用 Morris Traversal 可以使得空间复杂度变为O(1)。 它的主要思想就是利用叶子节点的左右子树是null,所以我们可以利用这个空间去存我们需要的节点,详细的可以参考94 题中序遍历。 publicList<Integer>preorderTraversal(TreeNoderoot){List<Integer>list=newArrayList<>();Tree...
5. Construct Binary Tree from Preorder and Inorder Traversal 与上题类似,我们知道preorder第一个元素一定是根节点,按照这个特性可以找出根节点在inorder中的位置,从该位置分开,左右两边分别就是左右子树。 class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if...
importjava.util.ArrayList;importjava.util.List;/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{public List<Integer>preorderTraversal(TreeNode root){ArrayList...
importjava.util.ArrayList;importjava.util.List;// 144. Binary Tree Preorder Traversal// https://leetcode.com/problems/binary-tree-preorder-traversal/description/// 二叉树的前序遍历// 时间复杂度: O(n), n为树的节点个数// 空间复杂度: O(h), h为树的高度publicclassSolution{publicclassTreeNod...
Binary tree traversal: Preorder, Inorder, and Postorder In order to illustrate few of the binary tree traversals, let us consider the below binary tree: Preorder traversal: To traverse a binary tree in Preorder, following operations are carried-out (i) Visit the root, (ii) Traverse the le...
Binary search tree with all the three recursive and non<br>recursive traversals<br><br>. BINARY SEARCH TREE is a Data Structures source code in C++ programming language. Visit us @ Source Codes World.com for Data Structures projects, final year projects