#include<bits/stdc++.h>
using namespace std;int n, a[109];
bool vst[109];
stack <int> s;intmain(){
cin >> n;for(int i =1; i <= n; i ++) cin >> a[i];
s.push(1);
vst[1]= true;while(s.size()){int u = s.top();int l = u *2;int r = u *2+1;if(a[l]&&!vst[l]){
s.push(l);
vst[l]= true;}else{
s.pop();
cout << a[u]<<' ';if(a[r]&&!vst[r]){
s.push(r);
vst[r]= true;}}}return0;}/*
7
10 5 15 1 6 12 20
7
10 1 11 0 6 0 12
*/
596 最小子树
publicclassSolution{publicintsum(TreeNode root){if(root == null)return0;return root.val +sum(root.left)+sum(root.right);}public TreeNode findSubtree(TreeNode root){if(root == null)return null;
TreeNode l =findSubtree(root.left);
TreeNode r =findSubtree(root.right);
TreeNode ans = root;if(l != null &&sum(l)<sum(ans)) ans = l;if(r != null &&sum(r)<sum(ans)) ans = r;return ans;}}
597 具有最大平均数的子树
publicclassSolution{publicintcount(TreeNode root){if(root == null)return0;return1+count(root.left)+count(root.right);}publicdoublesum(TreeNode root){if(root == null)return0;return root.val +sum(root.left)+sum(root.right);}public TreeNode findSubtree2(TreeNode root){if(root == null)return null;
TreeNode l =findSubtree2(root.left);
TreeNode r =findSubtree2(root.right);
TreeNode ans = root;if(l != null &&sum(l)/count(l)>sum(ans)/count(ans)) ans = l;if(r != null &&sum(r)/count(r)>sum(ans)/count(ans)) ans = r;return ans;}}
88 最近公共祖先
publicclassSolution{//如果树上有A和B的话,返回LCA(A,B)//如果树上只有一个结点的话,返回该结点public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B){if(root == null)return null;if(root == A || root == B)return root;
TreeNode l =lowestCommonAncestor(root.left, A, B);
TreeNode r =lowestCommonAncestor(root.right, A, B);if(l != null && r != null)return root;//A和B一左一右if(l != null)return l;//A和B都在左边(默认了在树上一定能找到A和B)if(r != null)return r;//A和B都在右边(默认了在树上一定能找到A和B)return null;//两边都没有}}
474 最近公共祖先 II
publicclassSolution{public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root, ParentTreeNode A, ParentTreeNode B){
Set <ParentTreeNode> s =newHashSet<>();while(A != null){
s.add(A);
A = A.parent;}while(!s.contains(B)){
B = B.parent;}return B;}}
578 最近公共祖先 III
publicclassSolution{publicintcount(TreeNode root, TreeNode A, TreeNode B){if(root == null)return0;int res =0;if(root == A || root == B) res =1;return res +count(root.left, A, B)+count(root.right, A, B);}//返回LCA(A,B)public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B){if(root == null)return null;if(A == B)return A;
TreeNode l =lowestCommonAncestor3(root.left, A, B);
TreeNode r =lowestCommonAncestor3(root.right, A, B);if(l != null)return l;//LCA在左子树if(r != null)return r;//LCA在右子树if(count(root, A, B)==2)return root;return null;}}
480 二叉树的所有路径public class Solution { public List<String> binaryTreePaths(TreeNode root) { List <String> paths = new ArrayList <> (); if (root == null) { return paths; } if (root.left == nu