1、题目描述

2、解题思路
把任务拆解:寻找上边界、寻找左边界、寻找下边界、寻找右边界。
定义一个 list 存储结果。
1、寻找上边界
根节点就是上边界,值存入 list 中。
2、寻找左边界
如果 root 有左子树,就存在左边界:
1、从 root.left 开始,一直往下遍历左子树;
2、当走到某一个 node 发现没有左子树,但是有右子树,那么就用 node.right 继续往下遍历;
3、当遇到 node 没有左右子结点,说明已经到下边界了,这个 node 不加入到左边界中。
把遍历到的每一个节点的值依次加入到 list 中。
如果 root 没有左子树,则没有左边界,进入下一步寻找下边界。
3、寻找下边界
下边界即 root 的所有叶子节点,把叶子节点全部加入到 list 中。
4、寻找右边界
右边界的和左边界的操作一样,只不过把左和右进行互换,把值存入到 stack 中,最后 stack 倒出来实现逆序,加入到总 list 中。
3、解题代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if (root == null) return res;
if (!isLeaf(root)) res.add(root.val); // 根节点就是上边界
TreeNode t = root.left;
// 如果有左子树,那么就存在左边界,否则没有左边界
while (t != null) {
// 不是叶子节点,即为左边界
if (!isLeaf(t)) res.add(t.val);
if (t.left != null) {
t = t.left;
} else { // 当走到某一层的左边界节点没有左子节点,则拿它的右子节点继续遍历
t = t.right;
}
}
// 添加下边界
addLeaves(res, root);
// 添加右边界,定义一个栈来最后调转顺序
Stack<Integer> s = new Stack<>();
t = root.right;
while (t != null) {
if (!isLeaf(t)) {
s.push(t.val);
}
if (t.right != null) {
t = t.right;
} else {
t = t.left;
}
}
while (!s.empty()) {
res.add(s.pop());
}
return res;
}
public boolean isLeaf(TreeNode t) {
return t.left == null && t.right == null;
}
public void addLeaves(List<Integer> res, TreeNode root) {
if (isLeaf(root)) {
res.add(root.val);
} else {
// 左子树的叶子节点加入 res
if (root.left != null) addLeaves(res, root.left);
// 右子树的叶子节点加入 res
if (root.right != null) addLeaves(res, root.right);
}
}
}
259

被折叠的 条评论
为什么被折叠?



