二叉树的打印右视图

使用案列

`2 7 4 6`

代码

用C ++代码打印二叉树的右视图

```#include <bits/stdc++.h>
using namespace std;

struct node{
int data;
node *left, *right;
};

node* create(int data){
node* tmp = new node();
tmp->data = data;
tmp->left = tmp->right = NULL;
return tmp;
}

void printRightView(node* root, int level, int &max_level){
if(root){
if(level > max_level){
max_level = level;
cout << root->data <<" ";
}
printRightView(root->right, level+1, max_level);
printRightView(root->left, level+1, max_level);
}
}

int main(){
node *root = create(2);
root->left = create(3);
root->right = create(7);
root->left->left = create(5);
root->left->right =create(4);
root->left->right->left = create(6);

int max_level = 0;
printRightView(root, 1, max_level);
}
```
`2 7 4 6`

Java代码以打印二叉树的右视图

```import java.util.*;

class node{
int data;
node left;
node right;
}

class Main{
static node create(int data){
node tmp = new node();
tmp.data = data;
tmp.left = null;
tmp.right = null;
return tmp;
}

static int max_level;
static void printRightView(node root, int level){
if(root != null){
if(level > max_level){
max_level = level;
System.out.print(root.data+" ");
}
printRightView(root.right, level+1);
printRightView(root.left, level+1);
}
}

public static void main(String[] args){
node root = create(2);
root.left = create(3);
root.right = create(7);
root.left.left = create(5);
root.left.right =create(4);
root.left.right.left = create(6);

max_level = 0;
printRightView(root, 1);
}
}```
`2 7 4 6`

复杂度分析

空间复杂度

O（1）。 如果不考虑编译器堆栈使用的空间，则否则 哦） 需要空间。