java实现 使用中序遍历来获取其最左边叶子节点和最右边叶子节点的值
时间: 2024-04-15 21:29:54 浏览: 19
下面是使用Java实现的代码示例,用于使用中序遍历获取二叉树的最左边叶子节点和最右边叶子节点的值:
```java
// 定义二叉树节点类
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
// 中序遍历获取最左边叶子节点和最右边叶子节点的值
class Solution {
private int leftLeafValue;
private int rightLeafValue;
public int[] getLeftAndRightLeafValues(TreeNode root) {
leftLeafValue = Integer.MIN_VALUE;
rightLeafValue = Integer.MIN_VALUE;
inorderTraversal(root);
return new int[]{leftLeafValue, rightLeafValue};
}
private void inorderTraversal(TreeNode node) {
if (node == null) {
return;
}
inorderTraversal(node.left);
// 更新最左边和最右边叶子节点的值
if (node.left == null && node.right == null) {
if (leftLeafValue == Integer.MIN_VALUE) {
leftLeafValue = node.val;
}
rightLeafValue = node.val;
}
inorderTraversal(node.right);
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
// 构建二叉树
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
// 获取最左边和最右边叶子节点的值
Solution solution = new Solution();
int[] leafValues = solution.getLeftAndRightLeafValues(root);
System.out.println("最左边叶子节点的值: " + leafValues[0]);
System.out.println("最右边叶子节点的值: " + leafValues[1]);
}
}
```
运行以上代码,将输出:
```
最左边叶子节点的值: 4
最右边叶子节点的值: 7
```
这表示给定的二叉树的最左边叶子节点的值为4,最右边叶子节点的值为7。请根据实际情况修改二叉树节点的构建和测试数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)