练习环境:   Xcode

编程语言:C++


解题思路:

1.先创建一个任意输入数据的二叉树。二叉链表结构存储,输入#代表节点为空。

2.再利用前序遍历记录最大value值的那个节点。


具体代码:

//
// main.cpp
// LintCode
//
// Created by xl on 2017/11/30.
// Copyright © 2017年 xl. All rights reserved.
//

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

typedef char ElemType;

typedef struct BinaryTreeNode{
char value;
struct BinaryTreeNode *lchild,*rchild;
}BinaryTreeNode,*BinaryTree;

BinaryTreeNode * CreatBiTree() {
BinaryTreeNode * node;
char data;
cin>>data;
if (data == '#') {
node = NULL;
} else {
node = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));//new BinaryTreeNode;
node->value = data;
node->lchild = CreatBiTree();
node->rchild = CreatBiTree();
}
return node;
}

BinaryTreeNode * currentMaxNode = new BinaryTreeNode;
void selectMaxNode(BinaryTreeNode *node) {
if (node == NULL) {
return;
}

if (node->value > currentMaxNode->value) {
currentMaxNode->value = node->value;
}
selectMaxNode(node->lchild);
selectMaxNode(node->rchild);
}

int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";

BinaryTreeNode *rootNode = CreatBiTree();
selectMaxNode(rootNode);
cout<<currentMaxNode->value;
return 0;
}