码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树相关题目

时间:2019-07-22 18:23:12      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:init   root   null   max   ||   最小值   validate   思路   bsp   

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 };

 

二叉树相关题目

标签:init   root   null   max   ||   最小值   validate   思路   bsp   

原文地址:https://www.cnblogs.com/sclczk/p/11227142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!