Boundary of Binary Tree
程序员文章站
2022-04-02 18:21:50
...
http://www.lintcode.com/zh-cn/problem/boundary-of-binary-tree/
import java.util.ArrayList;
import java.util.List;
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode
* @return: a list of integer
*/
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
// write your code here
List<Integer> res = new ArrayList<>();
if (root != null) {
List<TreeNode> leftList = new ArrayList<>();
List<TreeNode> bottomList = new ArrayList<>();
List<TreeNode> rightList = new ArrayList<>();
treeWalkLeft(root, leftList);
treeWalkRight(root, rightList);
treeWalkBottom(root, bottomList);
for (int i = 0; i < leftList.size(); i++) {
TreeNode treeNode = leftList.get(i);
res.add(treeNode.val);
}
for (int i = 0; i < bottomList.size(); i++) {
TreeNode treeNode = bottomList.get(i);
res.add(treeNode.val);
}
for (int i = rightList.size() - 1; i >= 0; i--) {
TreeNode treeNode = rightList.get(i);
if (!leftList.contains(treeNode)) {
res.add(treeNode.val);
}
}
}
return res;
}
private void treeWalkBottom(TreeNode root, List<TreeNode> bottomList) {
if (root == null) {
return;
}
TreeNode left = root.left;
TreeNode right = root.right;
if (left == null && right == null) {
// 是叶子节点
bottomList.add(root);
}
treeWalkBottom(left, bottomList);
treeWalkBottom(root.right, bottomList);
}
private void treeWalkRight(TreeNode root, List<TreeNode> rightList) {
if (root == null) {
return;
}
TreeNode left = root.left;
TreeNode right = root.right;
if (left == null && right == null) {
// 是叶子节点
return;
} else if (right != null) {
rightList.add(root);
treeWalkRight(root.right, rightList);
} else if (left != null) {
rightList.add(root);
treeWalkRight(left, rightList);
}
}
private void treeWalkLeft(TreeNode root, List<TreeNode> leftList) {
if (root == null) {
return;
}
TreeNode left = root.left;
TreeNode right = root.right;
if (left == null && right == null) {
// 是叶子节点
return;
} else if (left != null) {
leftList.add(root);
treeWalkLeft(root.left, leftList);
} else if (right != null) {
leftList.add(root);
treeWalkLeft(right, leftList);
}
}
}
推荐阅读
-
vue elementUI tree树形控件获取父节点ID的实例
-
Vue组件tree实现树形菜单
-
AngularJS递归指令实现Tree View效果示例
-
C# Serialization performance in System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,Newtonsoft.Json.JsonConvert and System.Text.Json.JsonSe
-
MySQL:Unsafe statement written to the binary log using statement format since BI
-
BZOJ5462: [APIO2018] 新家(K-D Tree)
-
CF1204D Kirk and a Binary String
-
Webpack之tree-starking 解析
-
bitmap 索引和 B-tree 索引在使用中如何选择
-
Liunx系统命令中tree命令详解