《Cracking the Coding Interview》——第4章:树和图——题目5

2014-03-19 04:11

题目:设计算法检查一棵二叉树是否为二叉搜索树。

解法:既然是二叉搜索树,也就是说左子树所有节点都小于根,右子树所有节点都大于根。如果你真的全都检查的话,那就做了很多重复工作。只需要将左边最靠右,和右边最靠左的节点和根进行比较,然后依照这个规则递归求解即可。

代码:

 1 // 4.5 Check if a binary tree is binary search tree.

 2 #include <cstdio>

 3 using namespace std;

 4 

 5 struct TreeNode {

 6     int val;

 7     TreeNode *left;

 8     TreeNode *right;

 9     

10     TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {};

11 };

12 

13 void constructBinaryTree(TreeNode *&root)

14 {

15     int val;

16     

17     scanf("%d", &val);

18     if (val <= 0) {

19         root = nullptr;

20     } else {

21         root = new TreeNode(val);

22 

23         constructBinaryTree(root->left);

24         constructBinaryTree(root->right);

25     }

26 }

27 

28 bool postorderTraversal(TreeNode *root, TreeNode *&left_most, TreeNode *&right_most)

29 {

30     TreeNode *ll, *lr, *rl, *rr;

31     bool res_left = true, res_right = true;

32     

33     if (root->left != nullptr) {

34         if (!postorderTraversal(root->left, ll, lr)) {

35             return false;

36         }

37         if (lr->val >= root->val) {

38             // all left nodes must be smaller than the root.

39             return false;

40         }

41     } else {

42         ll = lr = root;

43     }

44     

45     if (root->right != nullptr) {

46         if (!postorderTraversal(root->right, rl, rr)) {

47             return false;

48         }

49         if (rl->val <= root->val) {

50             // all right nodes must be greater than the root.

51             return false;

52         }

53     } else {

54         rl = rr = root;

55     }

56     left_most = ll;

57     right_most = rr;

58     

59     return true;

60 }

61 

62 void clearBinaryTree(TreeNode *&root) {

63     if (root == nullptr) {

64         return;

65     } else {

66         clearBinaryTree(root->left);

67         clearBinaryTree(root->right);

68         delete root;

69         root = nullptr;

70     }

71 }

72 

73 int main()

74 {

75     TreeNode *root;

76     TreeNode *left_most, *right_most;

77     

78     while (true) {

79         constructBinaryTree(root);

80         if (root == nullptr) {

81             break;

82         }

83         

84         left_most = right_most = nullptr;

85         if (postorderTraversal(root, left_most, right_most)) {

86             printf("Yes\n");

87         } else {

88             printf("No\n");

89         }

90         

91         clearBinaryTree(root);

92     }

93     

94     return 0;

95 }

 

你可能感兴趣的:(interview)