二叉树相关题目
Posted sclczk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树相关题目相关的知识,希望对你有一定的参考价值。
LeetCode 98. Validate Binary Search Tree(判断是否是二叉搜索树)
思路1:对树进行深度优先遍历,遍历到某个节点是判断该节点的左子树是否为二叉搜索树,右子树是否为二叉搜索树,左子树的最大值是否小于当前节点的值,右子树的最小值是否大于当前节点的值。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) 8 * ; 9 */ 10 class Solution 11 public: 12 bool isValidBST(TreeNode* root) 13 if(root == NULL) return true; 14 int maxv, minv; 15 return dfs(root, maxv, minv); 16 17 18 bool dfs(TreeNode* root, int &maxv, int &minv) 19 maxv = minv = root->val; 20 if(root->left) 21 int nowMaxv, nowMinv; 22 if(!dfs(root->left, nowMaxv, nowMinv)) 23 return false; 24 if(nowMaxv >= root->val) 25 return false; 26 maxv = max(maxv, nowMaxv); 27 minv = min(minv, nowMinv); 28 29 if(root->right) 30 int nowMaxv, nowMinv; 31 if (!dfs(root->right, nowMaxv, nowMinv)) 32 return false; 33 if (nowMinv <= root->val) 34 return false; 35 maxv = max(maxv, nowMaxv); 36 minv = min(minv, nowMinv); 37 38 return true; 39 40 ;
思路2:对树进行中序遍历,遍历的过程中判断当前值是否大于前一个值。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) 8 * ; 9 */ 10 class Solution 11 public: 12 bool isValidBST(TreeNode* root) 13 stack<TreeNode*> st; 14 int pre_val; 15 bool first_flag = true; 16 while(!st.empty() || root!=NULL) 17 while(root!=NULL) 18 st.push(root); 19 root = root->left; 20 21 root = st.top(); 22 st.pop(); 23 if(first_flag) 24 first_flag = false; 25 else if(root->val <= pre_val) 26 return false; 27 pre_val = root->val; 28 root = root->right; 29 30 return true; 31 32 ;
以上是关于二叉树相关题目的主要内容,如果未能解决你的问题,请参考以下文章