$L.left.val = R.right.val$ :即 L 的 左子节点 和 R 的 右子节点 对称;
$L.right.val = R.left.val$ :即 L 的 右子节点 和 R 的 左子节点 对称。
1 2 3 4 5 6 7 8 9 10 11
booljudge(TreeNode* left, TreeNode* right){ if (!left&&!right) returntrue; if (!left||!right||left->val!=right->val){ returnfalse; } return judge(left->left,right->right) && judge(left->right,right->left); } boolisSymmetric(TreeNode* root){ if (root==NULL) returntrue; return judge(root->left,root->right); }
【法二】队列
4.二叉树的深度
1 2 3 4 5
intmaxDepth(TreeNode* root){ if (root == NULL) return0; return max(maxDepth(root->left),maxDepth(root->right))+1; }
5.二叉搜索树
二叉搜索树的中序遍历为递增序列
求二叉搜索树的第k大节点
中序遍历的倒序:右、根、左
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: int ans; intkthLargest(TreeNode* root, int k){ if (root==NULL) return0; dfs(root,k); return ans; } voiddfs(TreeNode* root, int &k){ if (root==NULL) return; dfs(root->right,k); k--; if (k==0){ ans = root->val; return; } dfs(root->left,k); } };
6.判断是不是平衡二叉树
后序遍历+剪枝
时间复杂度 O(N): N 为树的节点数;最差情况下,需要递归遍历树的所有节点。
空间复杂度 O(N): 最差情况下(树退化为链表时),系统递归需要使用 O(N) 的栈空间。
1 2 3 4 5 6 7 8 9 10 11 12 13
intdepth(TreeNode* root){ if (root==NULL) return0; int l = depth(root->left); if (l==-1) return-1; int r = depth(root->right); if (r==-1) return-1; if (abs(l-r)<2) return max(l,r)+1; return-1; } boolisBalanced(TreeNode* root){ if (depth(root)==-1) returnfalse; elsereturntrue; }