Leetcode 1448. Count Good Nodes in Binary Tree (二叉树遍历题)

  1. Count Good Nodes in Binary Tree
    Medium
    Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
    Return the number of good nodes in the binary tree.

Example 1:

Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:

Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because “3” is higher than it.
Example 3:

Input: root = [1]
Output: 1
Explanation: Root is considered as good.

Constraints:

The number of nodes in the binary tree is in the range [1, 10^5].
Each node’s value is betwe

LeetCode上有多个关于二叉树遍历目,以下是一些常见目及对应的解思路和代码实现: ### 二叉树中序遍历 目描述:Given a binary tree, return the inorder traversal of its nodes’ values [^2]。 中序遍历是按照访问左子树——根节点——右子树的方式遍历二叉树,整个遍历过程天然具有递归的性质,可以直接用递归函数来模拟这一过程。以下是Python递归实现代码: ```python class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right) ``` 也可以使用非递归实现,关键点在于在弹出的时候进行节点值的访问,然后立即进入右子树。以下是C++非递归实现代码: ```cpp #include <vector> #include <stack> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; std::vector<int> inorderTraversal(TreeNode* root) { std::vector<int> res; if(root==NULL) return res; std::stack<TreeNode*> s; TreeNode* node=root; while(!s.empty() || node!=NULL) { while(node!=NULL) { s.push(node); node=node->left; } node=s.top(); s.pop(); res.push_back(node->val); node=node->right; } return res; } ``` ### 判断二叉树是否对称(层序遍历应用) 目虽未明确属于遍历目,但解使用了层序遍历思想。判断二叉树是否对称可以使用层序遍历的方法。以下是Java实现代码: ```java import java.util.LinkedList; import java.util.Queue; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } class Solution { public boolean isSymmetric(TreeNode root) { if(root == null || root.left == null && root.right == null) return true; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root.left); queue.offer(root.right); while(!queue.isEmpty()){ TreeNode left = queue.poll(); TreeNode right = queue.poll(); if(left == null && right == null) continue; if(left == null || right == null) return false; if(left.val != right.val) return false; queue.offer(left.left); queue.offer(right.right); queue.offer(left.right); queue.offer(right.left); } return true; } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值