BinaryTreeNode.h
// // BinaryTreeNode.h // BinaryTree // // Created by KeSen on 15/9/7. // Copyright (c) 2015年 KeSen. All rights reserved. // #import <Foundation/Foundation.h> @class BinaryTreeNode; @interface BinaryTreeNode : NSObject // 添加节点 + (BinaryTreeNode *)addTree:(BinaryTreeNode *)p addValue:(id)value; // 中序遍历 - (void)inOrderBinaryTree:(BinaryTreeNode *)p; // 翻转 - (BinaryTreeNode *)invertTree:(BinaryTreeNode *)p; @end
BinaryTreeNode.m
// // BinaryTreeNode.m // BinaryTree // // Created by KeSen on 15/9/7. // Copyright (c) 2015年 KeSen. All rights reserved. // #import "BinaryTreeNode.h" @implementation BinaryTreeNode { id val; BinaryTreeNode *left; BinaryTreeNode *right; } // 添加节点 + (BinaryTreeNode *)addTree:(BinaryTreeNode *)p addValue:(id)value { if (p == nil) { p = [[BinaryTreeNode alloc] init]; p->val = value; p->left = nil; p->right = nil; } else if ([value integerValue] < [p->val integerValue]) { p->left = [BinaryTreeNode addTree:p->left addValue:value]; } else { p->right = [BinaryTreeNode addTree:p->right addValue:value]; } return p; } // 中序遍历二叉树 - (void)inOrderBinaryTree:(BinaryTreeNode *)p { if (p != nil) { [self inOrderBinaryTree:p->left]; printf("%ld\n", (long)[p->val integerValue]); [self inOrderBinaryTree:p->right]; } } - (BinaryTreeNode *)invertTree:(BinaryTreeNode *)p { if (p == nil) { return nil; } p->left = [p invertTree:p->left]; p->right = [p invertTree:p->right]; BinaryTreeNode *temp = p->left; p->left = p->right; p->right = temp; return p; } @end
main.m
// // main.m // BinaryTree // // Created by KeSen on 15/9/7. // Copyright (c) 2015年 KeSen. All rights reserved. // #import <Foundation/Foundation.h> #import "BinaryTreeNode.h" int main(int argc, const char * argv[]) { @autoreleasepool { BinaryTreeNode *root = nil; for (id value in @[@(2), @(5), @(6), @(8), @(9)]) { root = [BinaryTreeNode addTree:root addValue:value]; } [root inOrderBinaryTree:root]; printf("\n"); BinaryTreeNode *invertTree = [root invertTree:root]; [invertTree inOrderBinaryTree:invertTree]; } return 0; }
输出结果为:
2
5
6
8
9
9
8
6
5
2
github:https://github.com/action456789/BinaryTree
参考:http://blog.devtang.com/blog/2015/06/16/talk-about-tech-interview/
http://www.cocoachina.com/bbs/read.php?tid=177907
时间: 2024-10-09 07:11:47