1publicvoidrecoverTree(TreeNode root) {2TreeNode cur =root;3while(cur!=null) {4if(cur.left!=null) {5TreeNode temp =cur.left;6while(temp.right!=null&& temp.right!=cur)7temp =temp.right;8if(temp.right==null) {9temp.right =cur;10cur =cur.left;11}12else{13temp.right=null;14//...
java版本的代码如下所示,首先是递归版本的代码: 1publicclassSolution {2publicList<Integer>inorderTraversal(TreeNode root) {3List<Integer> list =newArrayList<Integer>();4recur(list, root);5returnlist;6}78publicvoidrecur(List<Integer>list, TreeNode root){9if(root ==null)10return;11if(root.left...
publicList<Integer>inorderTraversal3(TreeNoderoot){List<Integer>ans=newArrayList<>();TreeNodecur=root;while(cur!=null){//情况 1if(cur.left==null){ans.add(cur.val);cur=cur.right;}else{//找左子树最右边的节点TreeNodepre=cur.left;while(pre.right!=null&&pre.right!=cur){pre=pre.right;}...
InOrdertraversal is extremely important because it also prints nodes of a binary search tree in thesorted order,but only if the given tree is abinary search tree. If you remember, in BST, the value of nodes in the left subtree is lower than the root, and values of the nodes in the r...
* TreeNode(int x) { val = x; } * } */classSolution{public List<Integer>inorderTraversal(TreeNode root){List<Integer>result=newLinkedList<>();TreeNode current=root;TreeNode prev=null;while(current!=null){// left firstif(current.left==null){result.add(current.val);current=current.right...
Write a Java program to get the in-order traversal of its nodes' values in a binary tree. Example:{10, 20, 30, 40, 50} Output: 40 20 50 10 30 Sample Binary TreeInorder Traversal:Sample Solution:Java Code:class Node { int key; Node left, right; public Node(int item) { // ...
{this.data=data;}}publicstaticvoidmain(String[]args){BinarySearchTreesearchTree=newBinarySearchTree();searchTree.insert(1);searchTree.insert(3);searchTree.insert(2);searchTree.insert(6);searchTree.insert(4);searchTree.insert(5);searchTree.insert(7);searchTree.printInOrder(searchTree.tree);//...
TreeNode root=newTreeNode(preorder[preorderBegin]);int rootIndex=0;for(int i=inorderBegin;i<=inorderEnd;i++){if(inorder[i]==preorder[preorderBegin]){rootIndex=i;break;}}int leftTreeSize=rootIndex-inorderBegin;root.left=buildTree(preorderBegin+1,preorderBegin+leftTreeSize,inorderBegin...
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...
Level-order traversal or breadth-first search starts traversing at the tree from root and explores all nodes at the present level before moving on to the nodes at the next depth level. Consider the below diagram: This is how the Level order traversal works in trees or any data structure. ...