常考数据结构与算法:输出二叉树的右视图
生活随笔
收集整理的這篇文章主要介紹了
常考数据结构与算法:输出二叉树的右视图
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述
請根據(jù)二叉樹的前序遍歷,中序遍歷恢復(fù)二叉樹,并打印出二叉樹的右視圖
?
上圖樹的右視圖為:{1,4,3,7}?
?
? 做此題之前可以先做下面3道題:
? ? 1.?常考數(shù)據(jù)結(jié)構(gòu)與算法:求二叉樹的層序遍歷
? ? 2.常考數(shù)據(jù)結(jié)構(gòu)與算法:二叉樹的之字形層序遍歷
? ? 3.常考數(shù)據(jù)結(jié)構(gòu)與算法:重建二叉樹
import java.util.ArrayList; import java.util.Stack;class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; } }public class ReConstructBinaryTreeShowRight {public static void main(String[] args) {int[] xianxu = {1,2,8,4,5,6,7,3};int[] zhongxu = {8,2,1,5,7,6,4,3};ReConstructBinaryTreeShowRight reConstructBinaryTreeShowRight = new ReConstructBinaryTreeShowRight();reConstructBinaryTreeShowRight.solve(xianxu,zhongxu);}private TreeNode findBinaryTree(int[] xianxu,int preStart, int preEnd, int[] zhongxu, int inStart, int inEnd){if(preStart > preEnd || inStart > inEnd){return null;}TreeNode root = new TreeNode(xianxu[preStart]);for (int i = inStart; i <=inEnd ; i++) {if(xianxu[preStart] == zhongxu[i]){// 根節(jié)點/*preStart+1,preStart+i-inStart 前序遍歷的左子樹inStart,i-1 中序遍歷的左子樹*/root.left = findBinaryTree(xianxu,preStart+1,preStart+i-inStart,zhongxu,inStart,i-1);/*preStart+1,preStart+i-inStart 前序遍歷的右子樹inStart,i-1 中序遍歷的右子樹*/root.right =findBinaryTree(xianxu,preStart+i-inStart+1,preEnd,zhongxu,i+1,inEnd);}}return root;}public int[] solve (int[] xianxu, int[] zhongxu) {TreeNode root = findBinaryTree(xianxu,0,xianxu.length-1, zhongxu,0, zhongxu.length-1);if(null == root){return null;}ArrayList<Integer> arrayList = new ArrayList<>();Stack<TreeNode> stack1 = new Stack<>();Stack<TreeNode> stack2 = new Stack<>();stack1.push(root);while(!stack1.isEmpty() || !stack2.isEmpty()){if(!stack1.isEmpty()){int len = stack1.size();while(!stack1.isEmpty()){TreeNode node = stack1.pop();if(node.right != null){stack2.push(node.right);}if(node.left != null){stack2.push(node.left);}if(len-1 == stack1.size()){arrayList.add(node.val);}}}else{while(!stack2.isEmpty()){TreeNode node = stack2.pop();if(node.left != null){stack1.push(node.left);}if(node.right != null){stack1.push(node.right);}if(stack2.size() == 0){arrayList.add(node.val);}}}}int[] arr = null;if(!arrayList.isEmpty()) {arr = new int[arrayList.size()];for (int i = 0; i < arrayList.size(); i++) {arr[i] = arrayList.get(i);}}return arr;} }?
總結(jié)
以上是生活随笔為你收集整理的常考数据结构与算法:输出二叉树的右视图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常考数据结构与算法:最长回文子串
- 下一篇: linux:进程